Skip to content

Instantly share code, notes, and snippets.

@dburles
Last active November 30, 2018 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dburles/8a3aa626ae12c305cc88917fd9fe3a49 to your computer and use it in GitHub Desktop.
Save dburles/8a3aa626ae12c305cc88917fd9fe3a49 to your computer and use it in GitHub Desktop.
import { useState } from 'react';
export const useFormState = initialState => {
const [formState, setFormState] = useState(initialState);
const onChange = event => {
const target = event.currentTarget;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
if (!name) {
throw Error('Field must have a name attribute!');
}
setFormState(state => ({ ...state, [name]: value }));
};
return [formState, onChange];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment