8

I'm wondering if there is a way to inject a Redux store middleware after the store creation?

I'd like to have something like:

injectMiddleware(store, [middleware1, middleware2]);

In a similar way, we can replace the root reducer on the fly after the store creation with replaceReducer https://redux.js.org/api-reference/store#replaceReducer.

Ben Smith
  • 19,589
  • 6
  • 65
  • 93
alexmngn
  • 9,107
  • 19
  • 70
  • 130

1 Answers1

6

You cannot use Redux to dynamically alter a store's middleware. However a library called redux-dynamic-middlewares does exist to achieve this.

Using this library you can add/remove/clear a store's middleware using calls such as:

// will add middleware to existing chain
addMiddleware(myMiddleware /*[, anotherMiddleware ... ]*/)

// will remove middleware from chain (only which was added by `addMiddleware`)
removeMiddleware(myMiddleware)

// clean all dynamic middlewares
resetMiddlewares()
Ben Smith
  • 19,589
  • 6
  • 65
  • 93