Skip to content

Instantly share code, notes, and snippets.

@AZagatti
Created October 28, 2020 02:00
Show Gist options
  • Save AZagatti/f8d53bfed5344d148bed2e5966db8663 to your computer and use it in GitHub Desktop.
Save AZagatti/f8d53bfed5344d148bed2e5966db8663 to your computer and use it in GitHub Desktop.
useForm
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