18.3.1.3 Thunk 생성 함수 만들기

    redux-thunk는 액션 생성 함수에서 일반 액션 객체를 반환하는 대신에 함수를 반환합니다. increaseAsyncdecreaseAsync 함수를 만들어 카운터 값을 비동기적으로 한번 변경시켜 봅시다.

    modules/counter.js

    import { createAction, handleActions } from 'redux-actions';
    
    const INCREASE = 'counter/INCREASE';
    const DECREASE = 'counter/DECREASE';
    
    export const increase = createAction(INCREASE);
    export const decrease = createAction(DECREASE);
    
    // 1 뒤에 increase 혹은 decrease 함수를 디스패치함
    export const increaseAsync = () => dispatch => {
      setTimeout(() => {
        dispatch(increase());
      }, 1000);
    };
    export const decreaseAsync = () => dispatch => {
      setTimeout(() => {
        dispatch(decrease());
      }, 1000);
    };
    
    const initialState = 0; // 상태는 꼭 객체일 필요가 없습니다. 숫자도 작동해요.
    
    const counter = handleActions(
      {
        [INCREASE]: state => state + 1,
        [DECREASE]: state => state - 1
      },
      initialState
    );
    
    export default counter;

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