javascriptreactjsreduxreact-reduxredux-middleware

How to pass arguments into custom Redux middleware?


I want to pass an argument into a custom Redux middleware. But I don't know how to use the argument inside the custom middleware.

Example:

import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers';

const customMiddleWare = store => next => action => {
  // how to use argument here?
};

const middlewares = [customMiddleWare(argument)];

const store = createStore(
  reducers,
  applyMiddleware(...middlewares)
);

Solution

  • As middlewares are functions you can make a wrapper function that will take your argument and return your middleware function which will have access to the provided argument.

    Example:

    const middlewareWrapper = customArgument => store => next => action =>
      console.log(customArgument);
    }
    
    const middlewares = [middlewareWrapper(argument)];
    
    const store = createStore(
      reducers,
      applyMiddleware(...middlewares)
    );