Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject middleware after redux store creation

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.

like image 338
alexmngn Avatar asked May 01 '18 10:05

alexmngn


People also ask

Is it necessary to use middleware in Redux?

Redux Middleware allows you to intercept every action sent to the reducer so you can make changes to the action or cancel the action. Middleware helps you with logging, error reporting, making asynchronous requests, and a whole lot more.

How do I bypass middleware in configureStore?

middleware ​ If this option is provided, it should contain all the middleware functions you want added to the store. configureStore will automatically pass those to applyMiddleware . If not provided, configureStore will call getDefaultMiddleware and use the array of middleware functions it returns.

How do I add multiple middleware to Redux?

You can simply pass the middlewares in the comma separated manner like the following code: const store = createStore(reducer, applyMiddleware(thunk, logger)); Note: Please import the applyMiddlware, thunk, and logger at the top.


1 Answers

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()
like image 56
Ben Smith Avatar answered Oct 24 '22 10:10

Ben Smith