Skip to content

Instantly share code, notes, and snippets.

@DJanoskova
Last active July 28, 2019 11:29
Show Gist options
  • Select an option

  • Save DJanoskova/77fc940283e5874e84f2ea7644cc9db3 to your computer and use it in GitHub Desktop.

Select an option

Save DJanoskova/77fc940283e5874e84f2ea7644cc9db3 to your computer and use it in GitHub Desktop.
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