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:
- Option 1: pollute my reducer calling the library, i.e. adding functions like
showSuccessToast()
right before returning the new state; - Option 2: create new actions like
ACTIONS_TYPES.SHOW_SUCCESS_TOAST
but this requires me to change alldispatch()
calls; - Option 3: create a new
cartNotificationReducer
adding functions likeshowSuccessToast()
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?