Ad

Redux Middleware Is Being Called After Reducer

- 1 answer

I have created a middleware like this:

export default store => next => action => {
    const res = next(action)

    console.log("Middleware", action.type)

    return res
} 

and my store configuration is:

import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import middleware from './middleware'

import rootReducer from './reducers';

export const history = createBrowserHistory();

const defaultState = {};

const composeEnhancers =
  typeof window === 'object' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
    }) : compose;

const enhancer = composeEnhancers(
  applyMiddleware(middleware, routerMiddleware(history)),
);

export const store = createStore(
  rootReducer(history),
  defaultState,
  enhancer
);

I also have a reducer and I am seeing in the logs and debugger that the reducer is called first and then the middleware. Any suggestions on what I have configured wrong?

Ad

Answer

If I remember correctly the reducer is being called when you invoke next(action). Move your console.log above that and that should give you the order of logs you want.

Ad
source: stackoverflow.com
Ad