패스트캠퍼스 메가바이트스쿨 Day 38 (8주차 목요일) - React로 로그인페이지,회원가입 구현하기

ctaaag·2022년 6월 3일
0
post-thumbnail

Today Topic : React로 로그인페이지, 회원가입 구현하기


🗝 Keywords
✅ 로그인 컴포넌트

✅ 마이페이지 컴포넌트



🚀 로그인 컴포넌트

import React, { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { loginUser } from "../reducer/userSlice.js";
import axios from "axios";

function LoginComponent() {
  const dispatch = useDispatch();

  const [id, setId] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [msg, setMsg] = useState("");

  useEffect(() => {}, [msg]);

  const userId = (event) => {
    setId(event.target.value);
  };

  const userPassword = (event) => {
    setPassword(event.target.value);
  };

  const LoginFunc = (e) => {
    e.preventDefault();
    setMsg("Loading...");
    let body = {
      id: id,
      password: password,
      // 키와 밸류가 같다면 id,password로 줄일 수 있음.
    };

    axios.post("https://st-fe34.herokuapp.com/api/login", body).then((res) => {
      setLoading(false);
      setTimeout(() => {
        setMsg("");
      }, 1500);
      const code = res.data.code;
      if (code === 400) {
        alert("비어있음");
      } else if (code === 401) {
        alert("존재하지 않는 id입니다");
      } else if (code === 402) {
        alert("존재하지 않는 pw입니다");
      } else {
        dispatch(loginUser(res.data.userInfo));
      }
    });
    setLoading(true);
  };
  return (
    <>
      <h1>LoginComponent</h1>
      <form onSubmit={LoginFunc}>
        <label htmlFor="id">ID : </label>
        <input type="text" id="id" onChange={userId} />
        <br />
        <label htmlFor="password">Password : </label>
        <input type="password" onChange={userPassword} />
        <br />
        <button disabled={loading} type="submit">
          로그인
        </button>
        <br />
        {msg}
      </form>
    </>
  );
}

export default LoginComponent;

🚀 마이페이지 컴포넌트

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { clearUser } from "../reducer/userSlice.js";

function MyPage() {
  const user = useSelector((state) => state.user);
  const dispatch = useDispatch();

  const LogoutFunc = () => {
    dispatch(clearUser(user));
    console.log(MyPage);
  };

  return (
    <>
      <h1>MyPage</h1>
      <p>{`${user.name} ${user.id}`}, 안녕하세요!</p>
      <button
        onClick={() => {
          LogoutFunc();
        }}

        로그아웃
      </button>
    </>
  );
}

profile
프로그래밍으로 지속가능한 세상을 꿈꾸며

0개의 댓글