Created
September 22, 2019 08:04
-
-
Save joshuaalpuerto/b73652a250408d624f81ef2744fae167 to your computer and use it in GitHub Desktop.
Basic form handling
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 { useReducer, useCallback } from 'react'; | |
export const INITIAL_STATE = {}; | |
function formReducer(state, action) { | |
switch (action.type) { | |
case '__reset__': | |
return INITIAL_STATE; | |
case action.type: | |
return { | |
...state, | |
[action.type]: action.payload, | |
}; | |
default: | |
return state; | |
} | |
} | |
const useForm = () => { | |
const [values, dispatch] = useReducer(formReducer, INITIAL_STATE); | |
const onChange = useCallback(evt => { | |
const { name: type, value: payload } = evt.target; | |
dispatch({ type, payload }); | |
}, []); | |
const resetForm = useCallback(() => { | |
dispatch({ type: '__reset__' }); | |
}, []); | |
return { | |
values, | |
onChange, | |
resetForm, | |
}; | |
}; | |
export default useForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment