const form = useFormState({
email: '',
password: ''
})
// returns form.setEmail, form.email, form.setPassword, and form.password
<input value={form.email} onChange={form.setEmail} />
<input value={form.password} onChange={form.setPassword} />
Last active
May 7, 2019 06:55
-
-
Save srph/2053cf063d2e0cda850055f27f0db424 to your computer and use it in GitHub Desktop.
React Hook: useFormState
This file contains hidden or 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 { useState, useMemo } from 'react' | |
/** | |
* @source https://gist.github.com/srph/2053cf063d2e0cda850055f27f0db424 | |
*/ | |
function useFormState(initial) { | |
const [state, setState] = useState(initial) | |
return useMemo(() => { | |
let out = {} | |
Object.keys(state).forEach(key => { | |
out[key] = state[key] | |
out[`set${ucFirst(key)}`] = (evt) => setState({ | |
...state, | |
[key]: evt.target.value | |
}) | |
}) | |
return out | |
}, [initial]) | |
} | |
export default useFormState | |
function ucFirst(str) { | |
return str.charAt(0).toUpperCase() + str.substr(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment