forked from wesbos/Advanced-React
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request wesbos#223 from bushbass/master
added lib/useForm.js to stepped solutions
- Loading branch information
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
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
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, | ||
}; | ||
} |