How to apply middleware selectively to reducers?

632 Views Asked by At

With reduxjs-toolkit I define my store and middleware something like this:

const store = configureStore({
    reducer: rootReducer,
    middleware: [reduxWebsocketMiddleware, adamBrownMiddleware]
});

However I only want to apply this middleware to certain reducers, not all. Specificially I want to apply websocket middleware to certain reducers, whereas in others I'm calling an API and this websocket middleware is not necessary.

It seems like adding another store to do this is an anti-pattern.

So how can I apply middleware only for certain reducers?

1

There are 1 best solutions below

2
phry On

You can always, in your middleware, check the action.type property (for example if it begins with "mySliceName/") and otherwise skip the rest of the middleware.

As you don't really give an example what your middleware is doing and why you want to limit it, it's not really possible to give you any more input than that.

This could look like this:

const middleware = api => next => action => {
  if (!action.type.startsWith("myWebsocketSlice/") { return next(action); }
 // normal middleware code here
}