redux-thunk

BigbrotherShin·2020년 1월 2일
0

1. 개념

redux-thunk는 리덕스에서 비동기 작업을 처리 할 때 가장 많이 사용하는 미들웨어입니다. 이 미들웨어를 사용하면 액션 객체가 아닌 함수를 디스패치 할 수 있습니다.

함수를 디스패치 할 때에는, 해당 함수에서 dispatch 와 getState 를 파라미터로 받아와주어야 합니다. 이 함수를 만들어주는 함수를 우리는 thunk 라고 부릅니다.

예시

const thunk = store => next => action =>
  typeof action === 'function'
    ? action(store.dispatch, store.getState)
    : next(action)

실제로, redux-thunk의 코드는 위와 유사합니다. 그냥 추가 기능을 위하여 몇 줄이 조금 더 추가됐을 뿐이죠.

사용 예시

 const getComments = () => async (dispatch, getState) => {
  // 이 안에서는 액션을 dispatch 할 수도 있고
  // getState를 사용하여 현재 상태도 조회 할 수 있습니다.
  const id = getState().post.activeId;

// 요청이 시작했음을 알리는 액션
dispatch({ type: 'GET_COMMENTS' });

// 댓글을 조회하는 프로미스를 반환하는 getComments 가 있다고 가정해봅시다.
try {
const comments = await api.getComments(id); // 요청을 하고
dispatch({ type: 'GET_COMMENTS_SUCCESS', id, comments }); // 성공 시
} catch (e) {
dispatch({ type: 'GET_COMMENTS_ERROR', error: e }); // 실패 시
}
}


- - -
*출처: <https://react.vlpt.us/redux-middleware/04-redux-thunk.html | velopert>
profile
JavaScript, Node.js 그리고 React를 배우는

0개의 댓글