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

34 lines
869 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 = (
2022-09-14 17:31:38 +00:00
e?: ChangeEvent,
setValue?: unknown,
formField?: string
) => {
2022-09-14 17:31:38 +00:00
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,
2022-09-14 17:31:38 +00:00
[formField]: setValue,
});
};
const handleSubmit = (e?: FormEvent) => {
e?.preventDefault();
onSubmit(formData);
};
return { formData, handleInputChange, handleSubmit };
}