Redux Thunk를 이용한 로그인/로그아웃 기능 구현

Redux Thunk는 Redux 미들웨어로, 비동기 작업을 처리하고 액션을 디스패치할 수 있게 해줍니다. 이를 이용하여 로그인 및 로그아웃 기능을 구현해보겠습니다.

1. Redux Thunk 설치

먼저 Redux Thunk를 설치해야 합니다. 명령 프롬프트 또는 터미널에서 다음 명령을 실행합니다:

npm install redux-thunk

2. 액션 생성자 작성

로그인 및 로그아웃을 위한 액션 생성자를 작성해야 합니다. loginUserlogoutUser 두 개의 액션 생성자를 만들어봅시다.

// actions.js

import { LOGIN_USER, LOGOUT_USER } from './actionTypes';

export const loginUser = (username, password) => {
  return dispatch => {
    // 서버에 로그인 요청을 보내는 비동기 작업 수행
    // 성공적으로 로그인한 경우
    dispatch({
      type: LOGIN_USER,
      payload: { username }
    });
  };
};

export const logoutUser = () => {
  return dispatch => {
    // 서버에 로그아웃 요청을 보내는 비동기 작업 수행
    // 성공적으로 로그아웃한 경우
    dispatch({
      type: LOGOUT_USER
    });
  };
};

3. 리듀서 작성

액션 생성자에서 디스패치한 액션을 처리하기 위해 리듀서를 작성해야 합니다. 사용자 상태를 저장하고 갱신하기 위해 userReducer를 작성합니다.

// reducers.js

import { LOGIN_USER, LOGOUT_USER } from './actionTypes';

const initialState = {
  isLoggedIn: false,
  username: ''
};

export const userReducer = (state = initialState, action) => {
  switch (action.type) {
    case LOGIN_USER:
      return {
        ...state,
        isLoggedIn: true,
        username: action.payload.username
      };
    case LOGOUT_USER:
      return {
        ...state,
        isLoggedIn: false,
        username: ''
      };
    default:
      return state;
  }
};

4. 스토어 구성

redux-thunk를 사용하기 위해 스토어를 구성해야 합니다. applyMiddleware 함수를 사용하여 미들웨어를 적용합니다.

// store.js

import { createStore, applyMiddleware } from 'redux';
import { userReducer } from './reducers';
import thunk from 'redux-thunk';

const store = createStore(userReducer, applyMiddleware(thunk));

export default store;

5. 컴포넌트에서 사용

로그인 및 로그아웃 기능을 컴포넌트에서 사용하려면 액션 생성자와 스토어를 연결해야 합니다. connect 함수를 사용하여 컴포넌트를 래핑하고, 액션 생성자를 mapDispatchToProps에 매핑합니다.

// Login.js

import React, { useState } from 'react';
import { connect } from 'react-redux';
import { loginUser } from './actions';

const Login = ({ loginUser }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = () => {
    // 로그인 액션 생성자 호출
    loginUser(username, password);
  };

  return (
    <div>
      <input
        type="text"
        value={username}
        onChange={e => setUsername(e.target.value)}
      />
      <input
        type="password"
        value={password}
        onChange={e => setPassword(e.target.value)}
      />
      <button onClick={handleLogin}>Login</button>
    </div>
  );
};

export default connect(null, { loginUser })(Login);
// Logout.js

import React from 'react';
import { connect } from 'react-redux';
import { logoutUser } from './actions';

const Logout = ({ logoutUser }) => {
  const handleLogout = () => {
    // 로그아웃 액션 생성자 호출
    logoutUser();
  };

  return (
    <div>
      <button onClick={handleLogout}>Logout</button>
    </div>
  );
};

export default connect(null, { logoutUser })(Logout);

컴포넌트에서 Redux 액션을 이용하여 로그인 및 로그아웃 기능을 사용할 수 있습니다. 위의 예시에서는 로그인 컴포넌트(Login)와 로그아웃 컴포넌트(Logout)를 작성하였습니다.

이제 Redux Thunk를 사용하여 로그인 및 로그아웃 기능을 구현할 수 있습니다. 이를 활용하여 웹 애플리케이션의 인증 기능을 효과적으로 구현할 수 있습니다.

참고 자료: