|
| 1 | +import { useState, useRef } from "react"; |
| 2 | +import { signIn } from "next-auth/client"; |
| 3 | +import { useRouter } from "next/router"; |
| 4 | + |
| 5 | +import classes from "./auth-form.module.css"; |
| 6 | + |
| 7 | +async function createUser(email, password) { |
| 8 | + const response = await fetch("/api/auth/signup", { |
| 9 | + method: "POST", |
| 10 | + body: JSON.stringify({ email, password }), |
| 11 | + headers: { "Content-Type": "application/json" }, |
| 12 | + }); |
| 13 | + const data = await response.json(); |
| 14 | + if (!response.ok) { |
| 15 | + throw new Error(data.message || "Something went wrong!"); |
| 16 | + } |
| 17 | + return data; |
| 18 | +} |
| 19 | + |
| 20 | +function AuthForm() { |
| 21 | + const router = useRouter(); |
| 22 | + const emailInputRef = useRef(); |
| 23 | + const passwordInputRef = useRef(); |
| 24 | + const [isLogin, setIsLogin] = useState(true); |
| 25 | + |
| 26 | + function switchAuthModeHandler() { |
| 27 | + setIsLogin((prevState) => !prevState); |
| 28 | + } |
| 29 | + |
| 30 | + async function submitHandler(event) { |
| 31 | + event.preventDefault(); |
| 32 | + const enteredEmail = emailInputRef.current.value; |
| 33 | + const enteredPassword = passwordInputRef.current.value; |
| 34 | + if (isLogin) { |
| 35 | + const result = await signIn("credentials", { |
| 36 | + redirect: false, |
| 37 | + email: enteredEmail, |
| 38 | + password: enteredPassword, |
| 39 | + }); |
| 40 | + if (!result.error) { |
| 41 | + router.replace("/profile"); |
| 42 | + } |
| 43 | + } else { |
| 44 | + try { |
| 45 | + const result = await createUser(enteredEmail, enteredPassword); |
| 46 | + console.log(result); |
| 47 | + } catch (error) { |
| 48 | + console.log(error); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return ( |
| 54 | + <section className={classes.auth}> |
| 55 | + <h1>{isLogin ? "Login" : "Sign Up"}</h1> |
| 56 | + <form onSubmit={submitHandler}> |
| 57 | + <div className={classes.control}> |
| 58 | + <label htmlFor="email">Your Email</label> |
| 59 | + <input type="email" id="email" required ref={emailInputRef} /> |
| 60 | + </div> |
| 61 | + <div className={classes.control}> |
| 62 | + <label htmlFor="password">Your Password</label> |
| 63 | + <input |
| 64 | + type="password" |
| 65 | + id="password" |
| 66 | + required |
| 67 | + ref={passwordInputRef} |
| 68 | + /> |
| 69 | + </div> |
| 70 | + <div className={classes.actions}> |
| 71 | + <button>{isLogin ? "Login" : "Create Account"}</button> |
| 72 | + <button |
| 73 | + type="button" |
| 74 | + className={classes.toggle} |
| 75 | + onClick={switchAuthModeHandler} |
| 76 | + > |
| 77 | + {isLogin ? "Create new account" : "Login with existing account"} |
| 78 | + </button> |
| 79 | + </div> |
| 80 | + </form> |
| 81 | + </section> |
| 82 | + ); |
| 83 | +} |
| 84 | + |
| 85 | +export default AuthForm; |
0 commit comments