React useReducer hook, how to handle multiple and unrelated types of actions?

Viewed 301

I'm using React hook useReducer to manage the state of a cart-like application. My cartReducer is used to handing adding/removing/changing quantity of items:

// utils/reducers.js
export const cartReducer = (state, action) => {
  switch (action.type) {
    case ACTIONS_TYPES.ADD_ITEM: {
      // ...
    }

    case ACTIONS_TYPES.REMOVE_ITEM: {
      // ...

    case ACTIONS_TYPES.EMPTY_CART: {
      // ...
    }

    case ACTIONS_TYPES.CHANGE_ITEM_QTY: {
      // ...
    }

    default: {
      throw new Error('Unrecognized action in cartReducer.');
    }
  }
};

Reducer cartReducer is used inside my cart component:

const [cart, dispatch] = useReducer(cartReducer, { items: [] });

Now, I'd like to add notifications using my preferred library, but I don't know how to handle it. I think I have 3 options:

  1. Option 1: pollute my reducer calling the library, i.e. adding functions like showSuccessToast() right before returning the new state;
  2. Option 2: create new actions like ACTIONS_TYPES.SHOW_SUCCESS_TOAST but this requires me to change all dispatch() calls;
  3. Option 3: create a new cartNotificationReducer adding functions like showSuccessToast()

I know that some of the option could be an anti-pattern, so I think that option 3 s the best. But useReducer accept only a single reducer... how can I combine them?

0 Answers
Related