본문 바로가기

React.js

Login 기능 개발 - axios, react-router-dom, localStorage

import React, { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";

function Login() {
  const [loading, setLoading] = useState(false);
  const [msg, setMsg] = useState(null);
  const [error, setError] = useState(null);
  
  const navigate = useNavigate();

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const LoginFunc = async (e) => {
    e.preventDefault();

    if (!email) {
      return alert("email을 입력하세요.");
    } else if (!password) {
      return alert("password를 입력하세요.");
    }

    try {
      setError(null);
      setLoading(true);

      await axios
        .post("http://localhost:80/login", {
          email: email,
          password: password,
        })
        .then((res) => {
          window.localStorage.setItem("user-name", res.data["user-name"]);

          navigate("/");
        })
        .catch((e) => {
          setMsg(e.response.data);
        });
    } catch (e) {
      setError(e);
    }
    setLoading(false);
  };

  if (loading) return <div>로딩중..</div>;
  if (error) return <div>에러가 발생했습니다</div>;

  return (
    <>
      <h1>LoginComponent</h1>
      <form onSubmit={LoginFunc}>
        <label htmlFor="email">email : </label>
        <input
          type="text"
          id="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />{" "}
        <br />

        <label htmlFor="password">Password : </label>
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />{" "}
        <br />
        
        <button type="submit" disabled={loading}>
          로그인
        </button>{" "}
      </form>

      { msg }
    </>
  );
}

export default Login;

 

 

 

 

 

 

'React.js' 카테고리의 다른 글

리액트 우분투 서버에 가장 쉽게 배포하기  (0) 2023.06.20