25 lines
633 B
TypeScript
25 lines
633 B
TypeScript
|
import { ChangeEvent, FormEvent, useState } from 'react';
|
||
|
|
||
|
export function useForm<T>(initialState: T, onSubmit: (data: T) => void) {
|
||
|
const [formData, setFormData] = useState<T>(initialState);
|
||
|
|
||
|
const handleInputChange = (
|
||
|
e: ChangeEvent,
|
||
|
setValue?: any,
|
||
|
formField?: string
|
||
|
) => {
|
||
|
const target = e.target as HTMLInputElement;
|
||
|
setFormData({
|
||
|
...formData,
|
||
|
[formField || target.name]: setValue ?? target.checked ?? target.value,
|
||
|
});
|
||
|
};
|
||
|
|
||
|
const handleSubmit = (e?: FormEvent) => {
|
||
|
e?.preventDefault();
|
||
|
onSubmit(formData);
|
||
|
};
|
||
|
|
||
|
return { formData, handleInputChange, handleSubmit };
|
||
|
}
|