Skip to content

Instantly share code, notes, and snippets.

@joshuaalpuerto
Created September 22, 2019 08:04
Show Gist options
  • Save joshuaalpuerto/b73652a250408d624f81ef2744fae167 to your computer and use it in GitHub Desktop.
Save joshuaalpuerto/b73652a250408d624f81ef2744fae167 to your computer and use it in GitHub Desktop.
Basic form handling
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