Migrating to createListenerMiddleware in Redux Toolkit 2.0
Provide an example of replacing the deprecated middleware API with the new createListenerMiddleware for intercepting and reacting to actions.
import { configureStore } from '@reduxjs/toolkit';
import { createListenerMiddleware, addListener } from '@reduxjs/toolkit';
// Define your middleware
const listenerMiddleware = createListenerMiddleware();
// Add listeners within the middleware
listenerMiddleware.startListening({
actionCreator: someAction,
effect: async (action, listenerApi) => {
// respond to action here
console.log('Action received:', action);
}
});
// Configure the store to use the listener middleware
export const store = configureStore({
reducer: {
// Your reducers go here
},
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(listenerMiddleware.middleware)
});
This example sets up the createListenerMiddleware in Redux Toolkit 2.0. It first imports the required functions from Redux Toolkit. It then defines the listener middleware using createListenerMiddleware and adds a listener for 'someAction' using startListening. Lastly, it configures the store, including the listener middleware alongside the default middleware provided by RTK.