Creating Custom Middleware

The below will give more detailed view of when code runs:

import { compose, createStore, applyMiddleware } from "redux";
// import logger from "redux-logger";

import { rootReducer } from "./root-reducer";

const loggerMiddleware = (store) => (next) => (action) => {
  if (!action.type) {
    return next(action);
  }
  console.log("type: ", action.type);
  console.log("payload: ", action.payload);
  console.log("currentState: ", store.getState());

  next(action);

  console.log('next state: ', store.getState());
};

const middleWares = [process.env.NODE_ENV !=='production' && loggerMiddleware].filter(Boolean);

const composedEnhancers = compose(applyMiddleware(...middleWares));

export const store = createStore(rootReducer, undefined, composedEnhancers);

The bit of code [process.env.NODE_ENV !=='production' && loggerMiddleware].filter(Boolean) makes sure this logger only runs in development mode.

Leave a Reply

Your email address will not be published. Required fields are marked *