24.2.5 로그인 구현

    회원가입을 구현할 때와 비슷하게 로그인 기능도 구현해 보겠습니다. LoginForm 컴포넌트를 다음과 같이 수정해 보세요.

    containers/auth/LoginForm.js

    import React, { useEffect } from 'react';
    import { useSelector, useDispatch } from 'react-redux';
    import { withRouter } from 'react-router-dom';
    import { changeField, initializeForm, login } from '../../modules/auth';
    import AuthForm from '../../components/auth/AuthForm';
    import { check } from '../../modules/user';
    
    const LoginForm = ({ history }) => {
      const dispatch = useDispatch();
      const { form, auth, authError, user } = useSelector(({ auth, user }) => ({
        form: auth.login,
        auth: auth.auth,
        authError: auth.authError,
        user: user.user
      }));
      // 인풋 변경 이벤트 핸들러
      const onChange = e => {
        (...)
      };
    
      // 폼 등록 이벤트 핸들러
      const onSubmit = e => {
        e.preventDefault();
        const { username, password } = form;
        dispatch(login({ username, password }));
      };
    
      // 컴포넌트가 처음 렌더링될 때 form을 초기화함
      useEffect(() => {
        dispatch(initializeForm('login'));
      }, [dispatch]);
    
      useEffect(() => {
        if (authError) {
          console.log('오류 발생');
          console.log(authError);
          return;
        }
        if (auth) {
          console.log('로그인 성공');
          dispatch(check());
        }
      }, [auth, authError, dispatch]);
    
      useEffect(() => {
        if (user) {
          history.push('/');
        }
      }, [history, user]);
    
      return (...);
    };
    
    export default withRouter(LoginForm);

     

    여기까지 다 작성했다면 http://localhost:3000/login에 들어가서 조금 전 회원가입에 성공한 계정으로 로그인해 보세요. http://localhost:3000/ 경로로 잘 이동되나요?

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.