I'm creating a simple Point of sale system and in my Cart reducer.
I need to check if the object is already in the Cart Array then increment the quantity. And if the Object does not exist push it into the Cart Array
The code is working as expected. But is there a better workaround ?
Cart Reducer
export const cartReducer = (state: IState, action: Actions) => {
const { uid } = action.payload
switch (action.type) {
case 'ADD_TO_CART': {
const cart_item = state.cart.filter(item => item.uid === uid)
if (cart_item.length > 0) {
return {
...state,
cart: state.cart.map(item => item.uid === uid ? { ...item, quantity: item.quantity + 1 } : item)
}
}
return {
...state,
cart: [...state.cart, action.payload]
}
}
}
}