-
-
Save velopert/e0d5a027f60a7368b2bb6f9277e3f742 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 { useReducer, useCallback } from 'react'; | |
function reducer(state, action) { | |
switch (action.type) { | |
case 'CHANGE': | |
return { | |
...state, | |
[action.name]: action.value | |
}; | |
case 'RESET': | |
return Object.keys(state).reduce((acc, current) => { | |
acc[current] = ''; | |
return acc; | |
}, {}); | |
default: | |
return state; | |
} | |
} | |
function useInputs(initialForm) { | |
const [form, dispatch] = useReducer(reducer, initialForm); | |
// change | |
const onChange = useCallback(e => { | |
const { name, value } = e.target; | |
dispatch({ type: 'CHANGE', name, value }); | |
}, []); | |
const reset = useCallback(() => dispatch({ type: 'RESET' }), []); | |
return [form, onChange, reset]; | |
} | |
export default useInputs; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment