[React] redux-thunk

jiseong·2021년 10월 19일
0

T I Learned

목록 보기
104/291

redux-thunk

redux saga를 사용하면서 thunk는 어떤식으로 사용하는지 궁금해 검색을 해보았다.

둘 다 기본적으로 dispatch 되었을 때 비동기 로직을 처리 후에 reducer로 전달하지만 dispatch로 전달하는 액션의 차이가 존재한다.

saga에서는 액션 객체만 dispatch 할 수 있지만,

const INCREMENT_COUNTER = 'INCREMENT_COUNTER';

function increment() {
  return {
    type: INCREMENT_COUNTER,
  };
}

function incrementAsync() {
  return (dispatch) => {
    setTimeout(() => {
      // Yay! Can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 1000);
  };
}

// 액션 객체가 아닌 thunk 함수를 dispatch
store.dispatch(incrementAsync()); 

위의 코드처럼 thunk를 사용하게되면 액션 객체를 dispatch 할 수 있지만 함수를 생성하여 그 안에서 여러가지 작업을 할 수 있는 thunk 함수도 dispatch 할 수 있다.

만약에 saga를 이용해서 youtube api를 받아왔던 코드를 thunk로 이용한다면 아래와 같은 방식으로 작성 할 수 있다.

const getMusicList = (keyword) => async (dispatch, getState) => {

  try {
    console.log('음악 찾기 시작...', keyword);
    const data = await fetchPlayList(`${keyword} 플레이리스트`);
    
    dispatch(getMusicListSuccess(data));
  } catch (e) {
    console.log(e);
  }
}

현재로써는 thunk가 오히려 간편하게 이용할 수 있다고 생각이 되는데 나중에 프로젝트에 따라 적절한 선택을 할 수 있도록 thunk와 saga를 골고루 써봐야 할 것 같다..


Reference

0개의 댓글