All files / src/components/Auth/EmailPassword EmailPasswordLoginForm.tsx

0% Statements 0/59
0% Branches 0/22
0% Functions 0/7
0% Lines 0/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139                                                                                                                                                                                                                                                                                     
import { CircularProgress } from "@mui/material";
import { useState } from "react";
import CustomButton from "../../common/CustomButton/index.tsx";
import { useLocation, useNavigate } from "react-router-dom";
import { useLoginMutation } from "../../../store/features/auth/api/loginApi.ts";
import { Toast } from "../../Toast.tsx";
import CustomInput from "../../Inputs/CustomInput.tsx";
import { InputTypes } from "../../../types/inputs/inputTypes.ts";
import ShowPasswordIcon from "./ShowPasswordIcon.tsx";
 
function EmailPasswordLoginForm() {
  const navigate = useNavigate();
  const location = useLocation();
  const [triggerLogin, { isLoading }] = useLoginMutation();
  const from = location.state?.from?.pathname || "/";
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [toastOpen, setToastOpen] = useState(false);
  const [toastMsg, setToastMsg] = useState("");
  const [toastType, setToastType] = useState("success");
  const [errors, setErrors] = useState({
    email: "",
    password: "",
  });
 
  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword);
  };
 
  const handleOpenToast = (msg: string, toastType: string) => {
    setToastMsg(msg);
    setToastType(toastType);
    setToastOpen(true);
  };
 
  const handleCloseToast = () => {
    setToastOpen(false);
  };
 
  const validate = () => {
    const newErrors = structuredClone(errors);
    Iif (!email) {
      newErrors.email = "Email is required";
    }
    Iif (!password) {
      newErrors.password = "Password is required";
    }
    setErrors(newErrors);
    return Object.keys(newErrors).every((key) => !newErrors[key]);
  };
 
  const handleSubmit = async (e) => {
    e.preventDefault();
    Iif (!validate()) return;
    try {
      const data = {
        email: email,
        password: password,
      };
      await triggerLogin(data).unwrap();
      setEmail("");
      setPassword("");
      handleOpenToast("Login Successful!", "success");
      navigate(from, { replace: true });
    } catch (err) {
      console.error(err);
      let error = "Login Failed";
      if (!err) {
        error = "No Server Response";
      } else if ((err as any)?.status === 400) {
        error =
          (err as any).data?.non_field_errors?.[0] ??
          (err as any).data?.[Object.keys((err as any)?.data ?? {})?.[0]];
      } else Iif ((err as any)?.status === 401) {
        error = "Unauthorized";
      }
      handleOpenToast(error, "error");
    }
  };
 
  return (
    <form onSubmit={handleSubmit} className="w-full">
      <div className="flex flex-col gap-2 my-2 w-full">
        <CustomInput
          inputType={InputTypes.TEXT}
          disabled={isLoading}
          value={email}
          handleChange={setEmail}
          placeholder="Enter Email"
          className="!w-full"
          containerClassName="!w-full"
          error={errors.email}
        />
        <CustomInput
          inputType={InputTypes.TEXT}
          disabled={isLoading}
          type={showPassword ? "text" : "password"}
          value={password}
          handleChange={setPassword}
          placeholder="Enter Password"
          className="!w-full border-none"
          containerClassName={`!w-full border rounded p-1 ${
            errors.password ? "border-red-500" : ""
          }`}
          error={errors.password}
          suffix={
            password && (
              <ShowPasswordIcon
                togglePasswordVisibility={togglePasswordVisibility}
              />
            )
          }
        />
      </div>
 
      <CustomButton
        className="!bg-violet-500 !text-white !text-sm w-full !justify-center hover:!bg-transparent hover:!text-violet-500 p-2 font-normal"
        onClick={handleSubmit}>
        {isLoading ? (
          <CircularProgress style={{ color: "inherit !important" }} size={20} />
        ) : (
          "Login"
        )}
      </CustomButton>
 
      <Toast
        open={toastOpen}
        handleClose={handleCloseToast}
        message={toastMsg}
        severity={toastType}
        anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
      />
    </form>
  );
}
 
export default EmailPasswordLoginForm;