Last active
November 13, 2018 11:08
-
-
Save a-x-/23ff4ced27b2ae52cb4119d8add1a987 to your computer and use it in GitHub Desktop.
react hooks on getters/setters — useStateObj
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 from "react"; | |
import ReactDOM from "react-dom"; | |
import useStateObj from "use-state-obj"; | |
function App() { | |
var state = useStateObj({a:1}) | |
function handleClick() { | |
++state.a | |
} | |
return ( | |
<div className="App"> | |
<h1>Hello, {state.a}!</h1> | |
<h2>Start editing to see some magic happen!</h2> | |
<button onClick={ handleClick }>click</button> | |
</div> | |
); | |
}; | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<App />, rootElement); |
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
function useStateObj(props) { | |
const props_ = Object.entries(props).reduce((res, [key, val]) => { | |
const [v, setV] = useState(val); | |
res[key] = { get: () => v, set: (v) => setV(v) }; | |
return res; | |
}, {}); | |
return Object.defineProperties({}, props_); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment