| 1 | import { useEffect, useState } from 'react'; |
| 2 | |
| 3 | export default function useForm(initial = {}) { |
| 4 | // create a state object for our inputs |
| 5 | const [inputs, setInputs] = useState(initial); |
| 6 | const initialValues = Object.values(initial).join(''); |
| 7 | |
| 8 | useEffect(() => { |
| 9 | // This function runs when the things we are watching change |
| 10 | setInputs(initial); |
| 11 | }, [initialValues]); |
| 12 | |
| 13 | // { |
| 14 | // name: 'wes', |
| 15 | // description: 'nice shoes', |
| 16 | // price: 1000 |
| 17 | // } |
| 18 | |
| 19 | function handleChange(e) { |
| 20 | let { value, name, type } = e.target; |
| 21 | if (type === 'number') { |
| 22 | value = parseInt(value); |
| 23 | } |
| 24 | if (type === 'file') { |
| 25 | [value] = e.target.files; |
| 26 | } |
| 27 | setInputs({ |
| 28 | // copy the existing state |
| 29 | ...inputs, |
| 30 | [name]: value, |
| 31 | }); |
| 32 | } |
| 33 | |
| 34 | function resetForm() { |
| 35 | setInputs(initial); |
| 36 | } |
| 37 | |
| 38 | function clearForm() { |
| 39 | const blankState = Object.fromEntries( |
| 40 | Object.entries(inputs).map(([key, value]) => [key, '']) |
| 41 | ); |
| 42 | setInputs(blankState); |
| 43 | } |
| 44 | |
| 45 | // return the things we want to surface from this custom hook |
| 46 | return { |
| 47 | inputs, |
| 48 | handleChange, |
| 49 | resetForm, |
| 50 | clearForm, |
| 51 | }; |
| 52 | } |