<aside> 📌

DB 조회나 DB 데이터 비교는 시간이 걸리는 작업

DB에서 응답이 올 때까지 login 함수가 기다리게 하기 위함

</aside>


async/await 사용 이유

로그인 기능 분석

<aside> ✏️

데이터베이스에서 응답이 올 때까지 이 login 함수가 기다리도록 하기 위함

await을 쓰면, 응답이 도착할 때까지 함수가 멈추고 기다림

성공(success) → Promise resolved

실패(fail) → Promise rejected

프론트엔드에서 토큰을 삭제하는 방식으로 바로 처리 가능

</aside>

로그인 기능 구현 코드

import { useForm } from "react-hook-form";
.
.
.
function Login() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const onSubmit = async (data) => {
    const userInfo = {
      // Hook Form에서 받은 폼 값 - data
      email: data.email,
      password: data.password,
    };
    // 서버로 JSON 객체 전송
    await axios
      .post("<http://localhost:4001/users/login>", userInfo)
      .then((res) => {
        console.log(res.data);
        if (res.data) {
          toast.success("Loggedin Successfully");
          document.getElementById("my_modal_3").close();
          setTimeout(() => {
            window.location.reload();
            /* localStorage에 유저 정보 저장 - 페이지 이동해도 로그인 유지 위함
            localStorage는 문자열만 저장 가능. 객체 형태를 문자(JSON 형태)로 변환 */
            localStorage.setItem("Users", JSON.stringify(res.data.user));
          }, 1000);
        }
      })
      .catch((err) => {
        if (err.response) {
          console.log(err);
          toast.error("Error: " + err.response.data.message);
          setTimeout(() => {}, 2000);
        }
      });
  };
  .
  .
  .