Created
November 6, 2018 21:00
-
-
Save jimmycallin/fd81095bfc40bc1139f8859eb7e15f5a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, useState } from "react"; | |
import "./App.css"; | |
const useStateHistory = initialState => { | |
const [state, setState] = useState(initialState); | |
const [stateHistory, setStateHistory] = useState([state]); | |
const [historyIndex, setHistoryIndex] = useState(null); | |
const setStateWrapper = localState => { | |
if (historyIndex !== null) { | |
return setState(stateHistory[historyIndex]); | |
} | |
setStateHistory(stateHistory => { | |
const newStateHistory = [...stateHistory, localState]; | |
return newStateHistory; | |
}); | |
return setState(localState); | |
}; | |
const History = () => ( | |
<> | |
<button | |
onClick={() => { | |
setHistoryIndex(null); | |
setState(stateHistory[stateHistory.length - 1]); | |
}} | |
> | |
Reset | |
</button> | |
{stateHistory.map((val, index) => ( | |
<button | |
key={index} | |
onClick={() => { | |
setHistoryIndex(index); | |
setState(stateHistory[index]); | |
}} | |
> | |
{val} | |
</button> | |
))} | |
</> | |
); | |
return [state, setStateWrapper, History]; | |
}; | |
const StateHistoryPOC = () => { | |
const [state, setState, History] = useStateHistory(2); | |
return ( | |
<div> | |
<h2>Counter</h2> | |
{state} | |
<h2>Update counter</h2> | |
<button onClick={() => setState(state + 1)}>+</button> | |
<h2>History</h2> | |
<History /> | |
</div> | |
); | |
}; | |
class App extends Component { | |
render() { | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<StateHistoryPOC /> | |
</header> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment