Created
October 8, 2019 22:17
-
-
Save dusty/df5d8f74d04ff2d4a91799b90269cb01 to your computer and use it in GitHub Desktop.
useForm
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
import { useState, useEffect, useCallback } from "react"; | |
export const useForm = (initialState, formRef) => { | |
const [isValid, setValid] = useState(false); | |
const [errors, setErrors] = useState({}); | |
const [form, setForm] = useState(initialState); | |
const checkValidity = useCallback(() => { | |
if (formRef && formRef.current) { | |
const validity = formRef.current.checkValidity(); | |
const formData = new FormData(formRef.current); | |
const newErrors = [...formData.keys()].reduce((acc, key) => { | |
acc[key] = formRef.current.elements[key].validationMessage; | |
return acc; | |
}, {}); | |
setValid(validity); | |
setErrors(newErrors); | |
} | |
}, [formRef]); | |
// re-run checkValidity when the form object is changed | |
// for example, when selecting a row in a table | |
useEffect(() => checkValidity(), [checkValidity, form]); | |
const onChange = ({ target }) => { | |
const name = target.name; | |
const value = target.type === "checkbox" ? target.checked : target.value; | |
checkValidity(); | |
setForm({ ...form, [name]: value }); | |
}; | |
return { form, setForm, onChange, isValid, errors }; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment