mekasu0124

Untitled

Nov 4th, 2023
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {
  2.   LoginContainer, FormContainer, Form,
  3.   Box, Label, ConfirmationLabel, Input, Button
  4. } from '../styles/pages/login.style';
  5. import React, { useRef, useState } from 'react';
  6. import { useNavigate } from 'react-router-dom';
  7. import api from '../api';
  8.  
  9. export default function Login() {
  10.   const formRef = useRef();
  11.   const navigate = useNavigate("");
  12.   const [userNotFound, setUserNotFound] = useState(false);
  13.  
  14.   const errorMessage = userNotFound ? "Email/Password Does Not Exist!" : null;
  15.  
  16.   const handleFormSubmit = async (event) => {
  17.     event.preventDefault();
  18.  
  19.     const form = formRef.current;
  20.     const formData = new FormData(form);
  21.     const emailAddress = formData.get("email_address");
  22.     const password = formData.get("password");
  23.  
  24.     if (emailAddress.trim() === '' || password.trim() === '') {
  25.       alert("All Entries Are Required!");
  26.       return;
  27.     }
  28.  
  29.     const postData = { emailAddress, password };
  30.  
  31.     try {
  32.       await api.get("/login", postData);
  33.       form.reset();
  34.       navigate("/");
  35.     } catch (error) {
  36.       if (error.response.status === 409) {
  37.         setUserNotFound(true);
  38.         return;
  39.       }
  40.       else if (error.response.status === 400) {
  41.         alert(error.response.data.detail);
  42.         return;
  43.       }
  44.       else {
  45.         console.log(error);
  46.         return;
  47.       }
  48.     };
  49.   };
  50.  
  51.   return (
  52.     <LoginContainer className="container-fluid">
  53.       <FormContainer className="container-fluid">
  54.         <Form onSubmit={handleFormSubmit} ref={formRef}>
  55.           <Box className="mb-3">
  56.             <Label htmlFor="email_address" className="form-label">Email Address</Label>
  57.             <Input type="text"
  58.                   className="form-control"
  59.                   id="email_address"
  60.                   name="email_address" />
  61.           </Box>
  62.  
  63.           <Box className="mb-3">
  64.             <Label htmlFor="password" className="form-label">Password</Label>
  65.             <Input type="password"
  66.                   className="form-control"
  67.                   id="password"
  68.                   name="password" />                
  69.           </Box>
  70.  
  71.           {
  72.             userNotFound &&
  73.             <ConfirmationLabel>{ errorMessage }</ConfirmationLabel>
  74.           }
  75.  
  76.           <Button type="submit" className="btn">Login</Button>
  77.         </Form>
  78.       </FormContainer>
  79.     </LoginContainer>
  80.   );
  81. };
Advertisement
Add Comment
Please, Sign In to add comment