Created
October 28, 2020 02:00
-
-
Save AZagatti/f8d53bfed5344d148bed2e5966db8663 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 { useCallback, useState, ChangeEvent } from "react"; | |
function useForm<T>(initialData: T) { | |
const [values, setValues] = useState<T>(initialData); | |
const setValue = useCallback((key: string | null, value: string) => { | |
if (!key) return; | |
setValues((state) => ({ ...state, [key]: value })); | |
}, []); | |
const handleChange = useCallback( | |
(e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => { | |
const { value } = e.target; | |
setValue(e.target.getAttribute("name"), value); | |
}, | |
[setValue] | |
); | |
const clearForm = useCallback(() => { | |
setValues(initialData); | |
}, [initialData]); | |
return { values, setValue, handleChange, clearForm }; | |
} | |
export default useForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment