Custom Logging Middleware
Demonstrate how to create a simple middleware that logs every action dispatched to the Redux store, including action type and payload.
const customLoggingMiddleware = store => next => action => {
// Log the action's type and payload
console.log('Dispatching:', action.type, action.payload);
// Pass the action to the next middleware in the chain
let result = next(action);
// Log the new state
console.log('Next state:', store.getState());
return result;
};
This piece of the code creates a custom logging middleware function. When an action is dispatched, it logs the action's type and payload before passing the action to the next middleware or reducer in the chain. After the next middleware or reducer has modified the state, it logs the new state.
import { applyMiddleware, createStore } from 'redux';
import rootReducer from './reducers';
// Apply the middleware to the store
const store = createStore(
rootReducer,
applyMiddleware(customLoggingMiddleware)
);
Here, the custom logging middleware is applied to the Redux store during its creation. We're importing the `createStore` and `applyMiddleware` functions from Redux. The `rootReducer` represents all of the app's reducers combined into one. The `customLoggingMiddleware` is passed into `applyMiddleware` which is then provided to the store. This setup ensures that every action dispatched will go through the logging middleware.