Last active
July 28, 2019 11:29
-
-
Save DJanoskova/77fc940283e5874e84f2ea7644cc9db3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| export function useForm (defaultValues, invalidAttr = { error: true }) { | |
| const [values, setValues] = useState(defaultValues); | |
| const [mounted, setMounted] = useState(false); | |
| const [formErrors, setFormErrors] = useState([]); | |
| const handleError = useCallback((name, isValid) => { | |
| let errors = formErrors; | |
| const index = errors.findIndex(error => error === name); | |
| if (!isValid) { | |
| if (index < 0) errors.push(name); | |
| } else { | |
| if (index > -1) errors.splice(index, 1); | |
| } | |
| setFormErrors(errors); | |
| }, [formErrors]); | |
| useEffect(() => { | |
| setMounted(true); | |
| }, []); | |
| const useInput = (name, validation) => useFormInput({ | |
| name, | |
| validation, | |
| values, | |
| setValues, | |
| defaultInvalidAttr: invalidAttr, | |
| handleError | |
| }); | |
| return { | |
| values, | |
| setValues, | |
| useInput, | |
| errors: formErrors, | |
| isValid: mounted && !formErrors.length | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment