TIL 21.06.08

Jaemin Jung·2021년 6월 12일
0

Today I Learned

목록 보기
36/62
post-thumbnail

Redux-thunk

어플리케이션에서 Redux를 통해 상태를 관리할때에도 비동기적 작업은 피해가지 못한다.
redux-thunk는 Redux에서 비동기 작업을 처리 할 때 가장 많이 사용하는 미들웨어이다.
redux-thunk 소스코드는 14줄로 간단한편이다.

리덕스 store 자체만으로넌 action을 dspatch 하는 작업을 통한 간단한 동기적 업데이트만 할 수 있다.

thunk는 표현식을 감싸 계산을 지연시키는 함수이다.

// calculation of 1 + 2 is immediate
// x === 3
let x = 1 + 2;

// calculation of 1 + 2 is delayed
// foo can be called later to perform the calculation
// foo is a thunk!
let foo = () => 1 + 2;

이 미들웨어를 사용하면 함수를 디스패치 할 수 있다. 함수를 디스패치 할 때에는, 해당 함수에서 dispatch 와 getState 를 파라미터로 받아와주어야 한다. 이 함수를 만들어주는 함수를 thunk 라고 부른다.

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

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

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

참고사이트

https://velog.io/@eensungkim/Redux-stydyv.1.3-TIL-63%EC%9D%BC%EC%B0%A8
https://react-redux.js.org/api/hooks
https://react.vlpt.us/redux-middleware/04-redux-thunk.html

profile
내가 보려고 쓰는 블로그

0개의 댓글