| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- import fetchApi, { ApiMethods, ApiPaths } from "./../utils/api";
- import { FormEventHandler, useState } from "react";
- type useFormProps = {
- path: ApiPaths;
- query?: string;
- method: ApiMethods;
- };
- type FormMessage = {
- message: string;
- };
- type SuccessFormData = {
- [k: string]: FormDataEntryValue;
- };
- type SubmitHandler = FormEventHandler<HTMLFormElement>;
- type UseForm = {
- error?: FormMessage;
- loading: boolean;
- submitHandler: SubmitHandler;
- success?: FormMessage;
- successFormData?: SuccessFormData;
- };
- const useForm = ({ path, method, query }: useFormProps): UseForm => {
- const [error, setError] = useState<FormMessage>();
- const [loading, setLoading] = useState(false);
- const [success, setSuccess] = useState<FormMessage>();
- const [successFormData, setSuccessFormData] = useState<SuccessFormData>();
- const submitHandler: FormEventHandler<HTMLFormElement> = async (event) => {
- event.preventDefault();
- setLoading(true);
- const formData = new FormData(event.currentTarget);
- const body = Object.fromEntries(formData.entries());
- const { error, message } = await fetchApi({
- path,
- query,
- method,
- body,
- });
- if (error) {
- setLoading(false);
- setError({ message: error });
- } else {
- setSuccessFormData(body);
- setLoading(false);
- setSuccess({ message: message || "Success!" });
- }
- };
- return { error, loading, success, submitHandler, successFormData };
- };
- export default useForm;
|