Sfoglia il codice sorgente

Introduce useForm hook

Tatiana Inama 4 anni fa
parent
commit
ff994f5341
2 ha cambiato i file con 44 aggiunte e 22 eliminazioni
  1. 38 0
      hooks/useForm.ts
  2. 6 22
      pages/login.tsx

+ 38 - 0
hooks/useForm.ts

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

+ 6 - 22
pages/login.tsx

@@ -1,29 +1,13 @@
 import { NextPage } from "next";
-import { FormEventHandler, useState } from "react";
 import Layout from "../components/Layout";
-import fetchApi, { ApiMethods, ApiPaths } from "../utils/api";
-
-type FormError = {
-  message: string;
-};
+import useForm from "../hooks/useForm";
+import { ApiMethods, ApiPaths } from "../utils/api";
 
 const Login: NextPage = () => {
-  const [error, setError] = useState<FormError | null>();
-
-  const submitHandler: FormEventHandler<HTMLFormElement> = async (event) => {
-    event.preventDefault();
-    const formData = new FormData(event.currentTarget);
-    const { error, message } = await fetchApi({
-      method: ApiMethods.POST,
-      path: ApiPaths.Login,
-      body: Object.fromEntries(formData.entries()),
-    });
-    if (error) {
-      setError({ message: error });
-    } else {
-      console.log(message);
-    }
-  };
+  const { error, submitHandler } = useForm({
+    path: ApiPaths.Login,
+    method: ApiMethods.POST,
+  });
 
   return (
     <Layout>