Skip to content

Instantly share code, notes, and snippets.

@tommyp
Created January 17, 2022 14:24
Show Gist options
  • Save tommyp/f9bc1e824b3743c223e91df7b20d7470 to your computer and use it in GitHub Desktop.
Save tommyp/f9bc1e824b3743c223e91df7b20d7470 to your computer and use it in GitHub Desktop.
/* 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