Redux 공식 홈페이지 따라하기

Redux 따라 만들어보기 (8) - 비동기 처리기 미들웨어

vitamin3000 2025. 1. 29. 16:19

이번 포스트에서는 직접 비동기 처리 미들웨어를 만들어보고자 한다.

 

비동기 처리 미들웨어는 기존의 함수와 다르게 증가값을 매개변수로 입력받아 그 값만큼 더할 것이다.

 

기존의 미들웨어 구조를 만들어주고  

const middleware = store => dispatch => action => {
  dispatch(action)
}

 

비동기 관련 함수를 작성한다

const asyncRouter = jobs => store => next => action => {
  asyncIncrease()
}

function asyncIncrease() {
  setTimeout(() => {
    dispatch(Actions.increase(20))
  }, 3000)
}

 

늘어난 매개변수 값만큼 store도 수정해야한다 (4개로)

const store = createStore(reducer, [logger, asyncRouter(asyncIncrease)]);

 

하지만 지금 작성한 코드는 함수형태이므로 사용하기위해 객체로 변환해야 한다.

const asyncJobs = {
  [ASYNC_INCREASE_COUNTER] :  function (){
    setTimeout(() => {
      dispatch(Actions.increase(20))
    }, 3000)
  }
}

 

KEY: VALUE 형태를 갖으니 비동기 처리기 미들웨어인 asyncRouter에서 키에 매칭되는 action type이 들어오면 

asyncJobs에 작성한 key가 들어오면 알맞은 처리를 하면 된다

 

우선, Object를 분해하여 jobs배열에서 찾아야하겠죠?

const asyncRouter = jobs => store => next => action => {
  const matchJob = Object.entries(jobs).find(([type]) => action.type === type);
  if(matchJob){
    matchJob[1](store,action);
  }else {
    next(action);
  }
  asyncIncrease()
}

const asyncJobs = {
  [ASYNC_INCREASE_COUNTER] :  function (store,action){
    setTimeout(() => {
      store.dispatch(Actions.increase(20))
    }, 3000)
  }
}

 

reducer.js에서도 매개변수 값에 대한 처리를 추가하고, 기존의 ASYNC_INCREASE 처리를 삭제한다

export default function reducer(state = InitializeState, action) {
  switch(action.type) {
    case Actions.INCREASE_COUNTER:
      if (action.payload){
        return { ...state, counter: state.counter === undefined ? 1 : state.counter + action.payload };
      }else{
        return { ...state, counter: state.counter === undefined ? 1 : state.counter + 1 };
      }
    case Actions.DECREASE_COUNTER:
      return { ...state, counter: state.counter === undefined ? 0 : state.counter - 1 };
    case Actions.SET_COUNTER:
      return { ...state, counter: action.payload };
    default:
       return { ...state };
  }
}