[redux] custom middleware

dev stefanCho·2021년 10월 5일
0

redux

목록 보기
3/3

custom middleware를 만드는 방법

아래 예제코드는 codesandbox에서 확인할 수 있다.

  1. custom middleware 로직을 만든다.
  2. store에 applyMiddleware로 연결한다.



Example


1. custom middleware

// custom middleware
export const logger = (store) => {
  return (next) => {
    return (action) => {
      next(action);
      console.log("logger::action::", action);
    };
  };
};

store

  • store는 redux store의 instance를 의미한다.

next

  • next는 middleware로 받은 action을 다음 middleware (만약 다음 middleware가 없다면 reducer)로 넘겨주는 function이다.
  • next를 쓰지 않으면, reducer로 action이 dispatch되지 않는다. 따라서 reducer가 업데이트 되지 않는다면, next를 제대로 했는 지 확인하자.

action

  • action은 말 그대로 action이다.
// actions.js
import { COUNT_UP, COUNT_DOWN } from "./actionTypes";

const countUp = (payload) => ({
  type: COUNT_UP,
  payload: {
    number: payload
  }
});
const countDown = (payload) => ({
  type: COUNT_DOWN,
  payload: {
    number: payload
  }
});

export { countUp, countDown };

dispatch할 action은 우리가 잘 알고 있는 type과 payload를 갖고 있는 object이다.

2. store에 middleware 연결하기

아주 간단하다. applyMiddleware에 argument로 넣어주면 끝이다.

// store.js
import { createStore, applyMiddleware } from "redux";
import rootReducer from "./reducers";
import { logger } from "./middlewares/logger";

export default createStore(rootReducer, {}, applyMiddleware(logger));

Typescript Example

custom middleware가 ts인 경우는 아래 형태가 된다.

// custom middleware
import { Store } from 'redux';

export const logger = (store: Store) => {
  return (next: (action: Action) => void) => {
    return (action: Action) => {
      next(action);
      console.log("logger::action::", action);
    };
  };
};

store에서 dispatch와 getState만 destructure하면 아래처럼 될 것이다.

// =====================================================
// =================== reducers.js =====================
// =====================================================
import { combineReducers } from "redux";
import countReducer from "./count";

export default combineReducers({ countReducer });
export type RootState = ReturnType<typeof reducers>;
                                   
// =====================================================
// ============== custom-middleware.js =================
// =====================================================

import { Dispatch } from 'redux';
import { RootState } from './reducers';

// define action type--
interface CountUpAction {
  type: 'COUNT_UP';
  payload: {
    number: number;
  }
}

interface CountDownAction {
  type: 'COUNT_DOWN';
  payload: {
    number: number;
  }
}

type Action = 
  | CountUpAction
  | CountDownAction;
// --end define action type

export const logger = ({ 
  dispatch,
  getState
}: { 
  dispatch: Dispatch<Action>; 
  getState: () => RootState; 
}) => {
  return (next: (action: Action) => void) => {
    return (action: Action) => {
      next(action);
      console.log("logger::action::", action);
    };
  };
};
profile
Front-end Developer

0개의 댓글