diff --git a/stepped-solutions/23/useForm.js b/stepped-solutions/23/useForm.js new file mode 100644 index 000000000..a17db5a63 --- /dev/null +++ b/stepped-solutions/23/useForm.js @@ -0,0 +1,52 @@ +import { useEffect, useState } from 'react'; + +export default function useForm(initial = {}) { + // create a state object for our inputs + const [inputs, setInputs] = useState(initial); + const initialValues = Object.values(initial).join(''); + + useEffect(() => { + // This function runs when the things we are watching change + setInputs(initial); + }, [initialValues]); + + // { + // name: 'wes', + // description: 'nice shoes', + // price: 1000 + // } + + function handleChange(e) { + let { value, name, type } = e.target; + if (type === 'number') { + value = parseInt(value); + } + if (type === 'file') { + [value] = e.target.files; + } + setInputs({ + // copy the existing state + ...inputs, + [name]: value, + }); + } + + function resetForm() { + setInputs(initial); + } + + function clearForm() { + const blankState = Object.fromEntries( + Object.entries(inputs).map(([key, value]) => [key, '']) + ); + setInputs(blankState); + } + + // return the things we want to surface from this custom hook + return { + inputs, + handleChange, + resetForm, + clearForm, + }; +}