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

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