Преглед изворни кода

Store user data when logged in

Tatiana Inama пре 4 година
родитељ
комит
eca2a947d3
8 измењених фајлова са 89 додато и 42 уклоњено
  1. 2 1
      .eslintrc.json
  2. 55 26
      components/Nav.tsx
  3. 5 3
      context/UserContext.tsx
  4. 1 1
      hooks/useForm.ts
  5. 15 3
      pages/login.tsx
  6. 6 8
      pages/signup.tsx
  7. 4 0
      styles/globals.css
  8. 1 0
      tailwind.config.js

+ 2 - 1
.eslintrc.json

@@ -20,6 +20,7 @@
   "rules": {
     "no-console": "off",
     "strict": ["error", "global"],
-    "curly": "warn"
+    "curly": "warn",
+    "@typescript-eslint/no-empty-function": "off"
   }
 }

+ 55 - 26
components/Nav.tsx

@@ -1,29 +1,58 @@
-import { FC } from "react";
+import { FC, useContext } from "react";
+import { UserContext } from "../context/UserContext";
+import Link from "next/link";
+import { useRouter } from "next/router";
 
-const Nav: FC = () => (
-  <header className="bg-prisma-50 w-full min-h-nav flex items-end">
-    <nav className="w-full max-w-screen-lg flex mx-auto justify-between">
-      <ul className="flex">
-        <li className="">
-          <a href="#" className="py-7 px-4 block font-bold">
-            Prisma
-          </a>
-        </li>
-      </ul>
-      <ul className="flex">
-        <li className="">
-          <a href="#" className="py-7 px-4 block">
-            Sign up
-          </a>
-        </li>
-        <li className="">
-          <a href="#" className="py-7 px-4 block">
-            Log in
-          </a>
-        </li>
-      </ul>
-    </nav>
-  </header>
-);
+const Nav: FC = () => {
+  const context = useContext(UserContext);
+  const { pathname } = useRouter();
+  return (
+    <header className="bg-prisma-50 w-full min-h-nav flex items-end">
+      <nav className="w-full max-w-screen-lg flex mx-auto justify-between">
+        <ul className="flex">
+          <li className="">
+            <Link href="/">
+              <a className="py-7 px-4 block font-bold">Prisma</a>
+            </Link>
+          </li>
+        </ul>
+        <ul className="flex">
+          {context.user ? (
+            <li>
+              <span className="py-7 px-4 block">
+                Hello <b>{context.user.name}</b>
+              </span>
+            </li>
+          ) : (
+            <>
+              <li>
+                <Link href="/signup">
+                  <a
+                    className={`py-7 px-4 block ${
+                      pathname === "/signup" ? "font-bold" : ""
+                    }`}
+                  >
+                    Sign up
+                  </a>
+                </Link>
+              </li>
+              <li className="">
+                <Link href="/login">
+                  <a
+                    className={`py-7 px-4 block ${
+                      pathname === "/login" ? "font-bold" : ""
+                    }`}
+                  >
+                    Log in
+                  </a>
+                </Link>
+              </li>
+            </>
+          )}
+        </ul>
+      </nav>
+    </header>
+  );
+};
 
 export default Nav;

+ 5 - 3
context/UserContext.tsx

@@ -7,9 +7,11 @@ interface UserContextInterface {
   setUser: React.Dispatch<React.SetStateAction<User | undefined>>;
 }
 
-export const UserContext = React.createContext<UserContextInterface | null>(
-  null
-);
+export const UserContext = React.createContext<UserContextInterface>({
+  logged: false,
+  setLogged: () => {},
+  setUser: () => {},
+});
 
 const UserContextProvider: FC = ({ children }) => {
   const [user, setUser] = useState<User>();

+ 1 - 1
hooks/useForm.ts

@@ -6,7 +6,7 @@ type FormMessage = {
 };
 
 type Success = FormMessage & {
-  result: Partial<User>;
+  result: User;
 };
 
 type SubmitHandler = FormEventHandler<HTMLFormElement>;

+ 15 - 3
pages/login.tsx

@@ -3,18 +3,24 @@ import { useContext, useEffect } from "react";
 import Layout from "../components/Layout";
 import { UserContext } from "../context/UserContext";
 import useForm from "../hooks/useForm";
+import { useRouter } from "next/router";
 import api from "../utils/api";
 
 const Login: NextPage = () => {
   const context = useContext(UserContext);
+  const router = useRouter();
 
   const { error, submitHandler, success } = useForm(api.login);
 
   useEffect(() => {
     if (success && context) {
-      console.log(success.message, success.result, context);
+      context.setLogged(true);
+      context.setUser(success.result);
+      setTimeout(() => {
+        router.push("/");
+      }, 1000);
     }
-  }, [success, context]);
+  }, [success, context, router]);
 
   return (
     <Layout>
@@ -40,6 +46,7 @@ const Login: NextPage = () => {
             type="password"
             name="password"
             id="password"
+            minLength={6}
             className="form-input"
             placeholder="••••••"
             required
@@ -48,11 +55,16 @@ const Login: NextPage = () => {
         <button type="submit" className="form-button">
           Log in
         </button>
-        {error && (
+        {error && !success && (
           <div role="alert" className="form-alert-msg">
             {error.message}
           </div>
         )}
+        {success && (
+          <div role="alert" className="form-success-msg">{`${
+            success.message || "Logged in successfully!"
+          } Redirecting to home`}</div>
+        )}
       </form>
     </Layout>
   );

+ 6 - 8
pages/signup.tsx

@@ -1,5 +1,4 @@
 import { NextPage } from "next";
-import { useEffect } from "react";
 import Layout from "../components/Layout";
 import useForm from "../hooks/useForm";
 import api from "../utils/api";
@@ -7,12 +6,6 @@ import api from "../utils/api";
 const SignUp: NextPage = () => {
   const { submitHandler, error, success } = useForm(api.register);
 
-  useEffect(() => {
-    if (success) {
-      console.log(success);
-    }
-  }, [success]);
-
   return (
     <Layout>
       <form className="form" onSubmit={submitHandler}>
@@ -46,11 +39,16 @@ const SignUp: NextPage = () => {
         <button type="submit" className="form-button">
           Sign up
         </button>
-        {error && (
+        {error && !success && (
           <div role="alert" className="form-alert-msg">
             {error.message}
           </div>
         )}
+        {success && (
+          <div role="alert" className="form-success-msg">
+            User created correctly! Please, log in to continue
+          </div>
+        )}
       </form>
     </Layout>
   );

+ 4 - 0
styles/globals.css

@@ -44,4 +44,8 @@
   .form-alert-msg {
     @apply col-span-2 bg-red-200 p-4 text-center rounded font-bold text-red-900;
   }
+
+  .form-success-msg {
+    @apply col-span-2 bg-green-200 p-4 text-center rounded font-bold text-green-900;
+  }
 }

+ 1 - 0
tailwind.config.js

@@ -13,6 +13,7 @@ module.exports = {
       white: colors.white,
       black: colors.black,
       red: colors.red,
+      green: colors.green,
       prisma: {
         50: "#ebebeb",
         100: "#d2d2d2",