Blog>
Snippets

Slice Listener Middlewares in Redux

Show how to register a middleware listener that responds to actions dispatched for a specific slice using the new listener middleware feature in Redux.
import { createListenerMiddleware, addListener } from '@reduxjs/toolkit';

// Define the listener middleware
const listenerMiddleware = createListenerMiddleware();
First, we import the necessary functions from Redux Toolkit and create a new listener middleware.
import { someSlice } from './someSlice';

// Action matcher to filter actions of a specific slice
const isSomeSliceAction = action => action.type.startsWith(someSlice.name + '/');
Define an action matcher that will check if the dispatched action is part of someSlice.
listenerMiddleware.startListening({
    matcher: isSomeSliceAction,
    effect: async (action, listenerApi) => {
        // Your logic here runs when the action is matched
        console.log('Action from someSlice was dispatched:', action);
    }
});
Register a listener middleware that listens for specific actions from someSlice and runs the associated effect when the action is dispatched.
// Later, you must apply the `listenerMiddleware` to the store
import { configureStore } from '@reduxjs/toolkit';

const store = configureStore({
    reducer: {
        // ... your reducers here
    },
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().prepend(listenerMiddleware)
});
We apply the previously created listenerMiddleware to the Redux store using the configureStore function from Redux Toolkit.