Blog>
Snippets

Creating Custom Middleware in Redux-Saga

Demonstrate the process of writing a logging middleware that captures each action dispatched to the store, logs the action type, and the state before and after the action is processed.
function logger({ getState }) {
  return next => action => {
    console.log('will dispatch', action);

    // Call the next dispatch method in the middleware chain.
    const returnValue = next(action);

    console.log('state after dispatch', getState());

    // This will likely be the action itself, unless
    // a middleware further in chain changed it.
    return returnValue;
  };
}
This is a custom logging middleware for Redux that logs every action dispatched to the store. It first logs the action that is about to be dispatched, then calls the next middleware in the chain (or the reducer if there are no more middlewares). After the action has been processed, it logs the new state of the store.
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware, logger));
sagaMiddleware.run(rootSaga);
This code snippet sets up the Redux store, applies both the saga middleware and the custom logger middleware created in the previous step, and then runs the saga middleware with the rootSaga. This configuration allows you to see the actions that are dispatched and how the state changes in response, while still benefiting from the powerful effects management provided by Redux-Saga.