icynet-admin/lib/hooks/useForm.ts

27 lines
710 B
TypeScript
Raw Normal View History

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;
2022-09-01 14:23:11 +00:00
const checkedOrValue =
target.type === 'checkbox' ? target.checked : target.value;
setFormData({
...formData,
2022-09-01 14:23:11 +00:00
[formField || target.name]: setValue ?? checkedOrValue,
});
};
const handleSubmit = (e?: FormEvent) => {
e?.preventDefault();
onSubmit(formData);
};
return { formData, handleInputChange, handleSubmit };
}