Skip to content

Instantly share code, notes, and snippets.

@mfrancois3k
Forked from AZagatti/useForm.ts
Created February 21, 2022 02:37
Show Gist options
  • Save mfrancois3k/c98b049dc7014ff2f8340a077daee45d to your computer and use it in GitHub Desktop.
Save mfrancois3k/c98b049dc7014ff2f8340a077daee45d 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