reduxjs/redux-toolkit

Any way to remove middleware after it's added then use createDynamicMiddleware?

smff opened this issue · 3 comments

smff commented

I need to load and unload some middleware dynamically.

const dynamicMiddleware = createDynamicMiddleware();

dynamicMiddleware.add(someMiddleware)

So, any way to remove someMiddleware now?

no, there's no way to remove middleware once added.

as a reminder though, middleware can always choose not to run:

const myDisableableMiddleware = (api) => {
  let enabled = true
  return (next) => (action) => {
    if (enableMiddleware.match(action)) {
      enabled = true
    } else if (disableMiddleware.match(action)) {
      enabled = false
    }
    if (!enabled) return next(action)
    // middleware logic here
  }
}
smff commented

@EskiMojo14 Are there any plans for building delete function into createDynamicMiddleware?

no, it's an intentional design decision - the main reason we think you'd want to add a middleware after store setup is for bundle size/lazy loading reasons, and in that case there's no size benefit to unloading the middleware.

it also makes the types for dispatch inaccurate, as there would be no way of knowing that the overloads you've added are still there.

const listenerDispatch = store.dispatch(withMiddleware(listener.middleware))

store.dispatch(removeMiddleware(listener.middleware))

const unsubscribe = listenerDispatch(addListener({ type, effect }))
//    ^ would be typed as UnsubscribeFunction even though it's actually just the action since we removed the middleware