Redux Toolkit addListener action does not register dynamic middleware

Viewed 35

I'm trying to add a dynamic listener middleware with RTK but it does not seem to intercept actions.I use the special addListener action which by the docs should allow inject dynamic middleware from a React component.On Redux dev tools I see listenerMiddleware/add action logged, but after that I see no actions intercepted by the middleware.

import { addListener} from '@reduxjs/toolkit';
import { useDispatch } from 'react-redux';

const App = () => {
  const dispatch = useDispatch();
  useEffect(() => {
        const unsubscribe = dispatch(
        addListener({
            predicate: () => {
                return true;
            },
            effect: async (action, listenerApi) => {
                console.log('log', action);
                
            },
        })
    );
    return () => unsubscribe();
}, [])
}
1 Answers

You have to add the listener to your store - if you skip that step the middleware will also not listen to your store.

From the docs:

// Create the middleware instance and methods
const listenerMiddleware = createListenerMiddleware()

const store = configureStore({
  reducer: {
    todos: todosReducer,
  },
  // Add the listener middleware to the store.
  // NOTE: Since this can receive actions with functions inside,
  // it should go before the serializability check middleware
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().prepend(listenerMiddleware.middleware),
})
Related