Login.js 1.56 KB
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

import { dataForage } from "../utils/LocalForage";
import "../styles/Login.css";
import axios from "axios";

const Login = () => {
  console.log("visit Login");
  const [state, setState] = useState({
    id: "",
    pw: "",
  });

  const handleChangeState = (e) => {
    setState({
      ...state,
      [e.target.name]: e.target.value,
    });
  };

  const navigate = useNavigate();
  const login = async () => {
    const res = await axios.post("http://localhost:3001/login/", {
      id: state.id,
      pw: state.pw,
    });

    if (res.data === "login failed") alert("ID/PW를 확인해주세요");
    else {
      await dataForage.setItem("session", true);
      navigate("/");
    }
  };

  useEffect(() => {
    async function ifAlreadyLogined() {
      if (await dataForage.getItem("session")) navigate("/");
    }
    ifAlreadyLogined();
  }, [navigate]);

  return (
    <div className="Login">
      <div className="idpw">
        <input
          className="id"
          name="id"
          value={state.id}
          onChange={handleChangeState}
          onFocus={(e) => e.target.select()}
          placeholder="E-Campus ID"
        />
        <input
          className="pw"
          name="pw"
          value={state.pw}
          onChange={handleChangeState}
          onFocus={(e) => e.target.select()}
          placeholder="E-Campus Password"
          type="password"
        />
      </div>
      <button onClick={login}>Login</button>
    </div>
  );
};

export default Login;