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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With