Blog>
Snippets

Logging Middleware

Demonstrate a custom Redux middleware that logs every action dispatched to the store, including the action type and payload, as well as the state before and after the action is processed.
const loggingMiddleware = store => next => action => {
  // Display the action's type and payload
  console.log('Dispatching:', action.type);
  console.log('With payload:', action.payload);

  // Display the state before the action was processed
  console.log('State before:', store.getState());

  // Pass the action down the middleware chain
  const result = next(action);

  // Display the state after the action was processed
  console.log('State after:', store.getState());

  // Return the result of the next middleware or the action's direct outcome
  return result;
};
This loggingMiddleware logs the action's type and payload, the state before the action is dispatched, and the state after the action is processed, then returns the result.