Skip to content

Commit

Permalink
Merge pull request wesbos#223 from bushbass/master
Browse files Browse the repository at this point in the history
added lib/useForm.js to stepped solutions
  • Loading branch information
wesbos authored Feb 17, 2021
2 parents 34b865a + 7642f93 commit 5b86366
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions stepped-solutions/23/useForm.js
Original file line number Diff line number Diff line change
@@ -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,
};
}

0 comments on commit 5b86366

Please sign in to comment.