Dynamic Middleware Injection in Redux
Provide an example of dynamically adding custom logging middleware to the Redux store using the configureStore API from RTK 2.0.
import { configureStore } from '@reduxjs/toolkit';
// Define your custom logging middleware
const loggingMiddleware = store => next => action => {
console.log('Dispatching:', action);
let result = next(action);
console.log('Next state:', store.getState());
return result;
};
This is the custom logging middleware function that logs actions and states.
const store = configureStore({
reducer: rootReducer
// ... other store setup options
});
The Redux store is created using the configureStore API from RTK 2.0. The rootReducer is a placeholder for your actual root reducer.
store.injectMiddleware({
stage: 'before', // or 'after' depending on when you want the logging
middleware: loggingMiddleware
});
This dynamically injects the custom logging middleware into the store. The 'stage' option specifies when the middleware should run: before or after all other middlewares.