Redux-thunk 알아보기

UYeong·2021년 8월 16일
0

Redux

목록 보기
1/1

Redux-thunk 소개와 설치

redux-thunk는 redux의 미들웨어이다.
(미들웨어란 원하는곳에 기능을 추가해서 기능을 향상 시켜주는 역할을 하는 것이다.)
그래서 redux-thunk를 이용해 redux의 기능을 확장시켜 사용할 수 있다.

redux-thunk를 사용하면 action을 객체로 사용하지 않고 객체대신 비동기함수를 넣어도 동작할 수 있게 해준다.

github에 작성된 redux-thunk 문서를 보면 reduex-thunk의 전체 코드를 볼수있는데 https://github.com/reduxjs/redux-thunk 로 가면 소스폴더의 index.js 파일에

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => (next) => (action) => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

이렇게 redux-thunk의 전체 코드를 볼 수 있다. 한눈에 봐도 전체코드가 굉장히 짧다.
이제 npm i redux-thunk로 설치한 후 자신의 파일에 import (원하는이름) from 'redux-thunk'; 으로 불러와준뒤 applyMiddlewares에 applyMiddlewares(reduxThunk) 이렇게 넣어 사용하면 된다.

  • redux-thunk의 코드를 보면 3단 고차함수 미들웨어로 되어있고, dispatch
    getState 를 매개변수로 받아온다. 그리고 기존 redux에서는 action 타입이 객체 였지만 redux-thunk에서는 action type이 'function'일때도 동작을 한다는 것도 볼 수 있다.

Redux-thunk 사용 예시

action 타입이 function일때의 thunk함수의 예시를 보면
(https://github.com/reduxjs/redux-thunk 여기로 들어가면 README.md에서 볼수있다.)

const INCREMENT_COUNTER = 'INCREMENT_COUNTER';

//1. 동기 action creator 함수
function increment() {
  return {
    type: INCREMENT_COUNTER,
  };
}

//2. 비동기 action creator 함수
function incrementAsync() {
  return (dispatch) => {
    setTimeout(() => {
      // Yay! Can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 1000);
  };
}

원래 redux 에서는 위의 주석1번 처럼 action creator함수를 동기로만 사용할수 있었지만 밑의 주석2번을 보면 action creator 함수를 비동기로 만들어도 동작이 된다는 것을 알 수 있다.

이렇게 비동기로 만들어 사용하면 하나의 action creator 함수안에 여러개의 동기 action을 넣을 수 있어서 dispatch를 여러번 해줄수 있다는 장점이 있다.
대표적으로 axios를 사용하여 예를 들어 보면

//Thunk함수
const loginAction = () => {
  return (dispatch) => {
    dispatch(loginRequestAction());
    axios.post('/api/login')
      .then((res) => {
        dispatch(loginSuccessAction(res.data));
      })
      .catch((err) => {
        dispatch(loginFailureAction(err));
      })
  }
}

//1.Request
const loginRequestAction = (data) => {
  return {
    type: 'LOG_IN_REQUEST',
    data,
  }
};

//2.Success
const loginSuccessAction = (data) => {
  return {
    type: 'LOG_IN_SUCCESS',
    data,
  }
};

//3.Failure
const loginFailureAction = (data) => {
  return {
    type: 'LOG_IN_FAILURE',
    data,
  }
};

이렇게 객체를 리턴하는 3개의 action creator함수들을 비동기 action creator인 thunk함수를 추가해 여러번의 dispatch를 해줄수 있다.



profile
Create the brilliant service for the world

0개의 댓글