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?: unknown,
formField?: string
) => {
if (e && e.target) {
const target = e.target as HTMLInputElement;
formField = formField || target.name;
setValue =
setValue ??
(target.type === 'checkbox' ? target.checked : target.value);
} else if (!formField) {
throw new Error('Invalid invocation of the change method');
}
setFormData({
...formData,
[formField]: setValue,
});
};
const handleSubmit = (e?: FormEvent) => {
e?.preventDefault();
onSubmit(formData);
return { formData, handleInputChange, handleSubmit };