2

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?

gremo
  • 47,186
  • 75
  • 257
  • 421
  • Not sure if this is a duplicate: https://stackoverflow.com/questions/59200785/react-usereducer-how-to-combine-multiple-reducers. In the redux world, the combinereducers approach is standard. – David Hall Aug 31 '20 at 10:04
  • @DavidHall thanks for your comment, but I'm not using the redux library, so I can't use `combineReducer` function. – gremo Aug 31 '20 at 10:43
  • 1
    If you read down further in the answer linked above you will find discussion of non-redux solutions. – pilchard Aug 31 '20 at 11:43

0 Answers0