Side Effects in Middleware

Learn about the side effects in middleware.

In the previous lesson, we implemented a flow to handle side effects in action creators. Let’s take a moment and implement the exact same flow, this time in a middleware:

//Handling side effects in middleware
const cartMiddleware = ({ dispatch, getState }) => next => action => {
  next(action);

  if (action.type === ADD_ITEM_TO_CART) {
    dispatch(updateCart(item));

    if (getState().cart.items.length > 10) {
      dispatch(applyDiscount(20));
    }

    dispatch(showNotification(`${item.name} has been added to cart!`));
  }
};

At first glance, the code looks practically the same. However, this approach has at least one big advantage over the redux-thunk example: the side effects are triggered as a result of another action rather than the user’s interaction with the UI. This allows for easier debugging since we can trace all actions in the flow and identify what actions are sent as a result of others.

Get hands-on with 1400+ tech skills courses.