Last active
June 11, 2020 15:37
-
-
Save lucksp/3257e94208ef40fb82af46b006b3148f to your computer and use it in GitHub Desktop.
Custom Form Hook
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
import { useState, useEffect, useRef } from "react"; | |
const useCustomForm = ({ | |
initialValues, | |
onSubmit | |
}) => { | |
const [values, setValues] = useState(initialValues || {}); | |
const [errors, setErrors] = useState({}); | |
const [touched, setTouched] = useState({}); | |
const [onSubmitting, setOnSubmitting] = useState<boolean>(false); | |
const [onBlur, setOnBlur] = useState<boolean>(false); | |
const formRendered = useRef(true); | |
useEffect(() => { | |
if (!formRendered.current) { | |
setValues(initialValues); | |
setErrors({}); | |
setTouched({}); | |
setOnSubmitting(false); | |
setOnBlur(false); | |
} | |
formRendered.current = false; | |
}, [initialValues]); | |
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { | |
const { target } = event; | |
const { name, value } = target; | |
event.persist(); | |
setValues({ ...values, [name]: value }); | |
}; | |
const handleBlur = (event: React.ChangeEvent<HTMLInputElement>) => { | |
const { target } = event; | |
const { name } = target; | |
setTouched({ ...touched, [name]: true }); | |
setErrors({ ...errors }); | |
}; | |
const handleSubmit = (event: any) => { | |
if (event) event.preventDefault(); | |
setErrors({ ...errors }); | |
onSubmit({ values, errors }); | |
}; | |
return { | |
values, | |
errors, | |
touched, | |
handleChange, | |
handleBlur, | |
handleSubmit | |
}; | |
}; | |
export default useCustomForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment