Created
January 17, 2022 14:24
-
-
Save tommyp/f9bc1e824b3743c223e91df7b20d7470 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
/* eslint-disable prefer-const */ | |
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(() => { | |
setInputs(initial); | |
}, [initialValues]); | |
function handleChange(e) { | |
let { value, name, type } = e.target; | |
if (type === 'number') { | |
value = parseInt(value, 10); | |
} | |
if (type === 'file') { | |
[value] = e.target.files; | |
} | |
setInputs({ | |
...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 | |
return { | |
inputs, | |
handleChange, | |
resetForm, | |
clearForm, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment