redux thunk

Judo·2021년 1월 12일
0

참고문서

소개

  • 리덕스에서 비동기 작업을 처리할 때 사용하는 미들웨어
  • 액션 객체가 아닌 함수를 디스패치 할 수 있게한다.
  • 함수를 디스패치 할 때, 해당 함수에서 dispatch와 getState를 파라미터로 받아줌. 이 때 이 함수를 만들어주는 함수가 thunk
// thunk 함수 
export const increaseAsync = () => (dispatch, getState) => {
  setTimeout(() => dispatch(increase()), 1000)
}

export const decreaseAsync = () => (dispatch, getState) => {
  setTimeout(() => dispatch(decrease()), 1000)
}
  • 위 코드에서 thunk는 increaseAsync, decreaseAsync 함수
  • 두 thunk 함수가 dispatch와 getState를 파라미터로 받는 함수를 리턴한다.

설치

npm install redux-thunk

적용

  • redux-thunk를 사용하기 위해선 미들웨어를 스토어에 적용시켜줘야한다.
//index.js
다른건 생략...
import ReduxThunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';

const store = createStore(
	rootReducers, 
  	composeWithDevTools(applyMiddleware(ReduxThunk, logger))

)


ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
//counter.js
// 액션 타입
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';

// 액션 생성 함수
export const increase = () => ({ type: INCREASE });
export const decrease = () => ({ type: DECREASE });

// getState를 쓰지 않는다면 굳이 파라미터로 받아올 필요 없습니다.
export const increaseAsync = () => dispatch => {
  setTimeout(() => dispatch(increase()), 1000);
};
export const decreaseAsync = () => dispatch => {
  setTimeout(() => dispatch(decrease()), 1000);
};

// 초깃값 (상태가 객체가 아니라 그냥 숫자여도 상관 없습니다.)
const initialState = 0;

export default function counter(state = initialState, action) {
  switch (action.type) {
    case INCREASE:
      return state + 1;
    case DECREASE:
      return state - 1;
    default:
      return state;
  }
}
//CounterContainer.js
import React from 'react';
import Counter from '../components/Counter';
import { useSelector, useDispatch } from 'react-redux';
import { increaseAsync, decreaseAsync } from '../modules/counter';

function CounterContainer() {
  const number = useSelector(state => state.counter);
  const dispatch = useDispatch();

  const onIncrease = () => {
    dispatch(increaseAsync());
  };
 
  const onDecrease = () => {
    dispatch(decreaseAsync());
  };

  return (
    <Counter number={number} onIncrease={onIncrease} onDecrease={onDecrease} />
  );
}

export default CounterContainer;
  • 위 코드 CounterContainer.js를 보면 increaseAsync()를 호출하면 함수가 반환된다. 반환되는 함수는 비동기 호출(setTimeout)이 완료되면 dispatch(increase())를 호출한다.

더 공부하고 추가 작성..

profile
즐거운 코딩

0개의 댓글