This repository has been archived on 2024-06-14. You can view files and clone it, but cannot push or open issues or pull requests.
icynet-admin/lib/hooks/useForm.ts

27 lines
710 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;
const checkedOrValue =
target.type === 'checkbox' ? target.checked : target.value;
setFormData({
...formData,
[formField || target.name]: setValue ?? checkedOrValue,
});
};
const handleSubmit = (e?: FormEvent) => {
e?.preventDefault();
onSubmit(formData);
};
return { formData, handleInputChange, handleSubmit };
}