I am currently working on a React-Redux based Cart app, and I am experiencing the following problem:
When I continuously click the remove button in order to remove a product from my cart, the quantity goes below zero. Any solutions on how to end the quantity at 1 and then remove the the whole product from the front end when there is one left?
Below is my function:
case 'REMOVE_FROM_CART': return { ...state, cart: state.cart.filter(item => item.id !== action.payload.id), cart: state.cart.map(item => item.id === action.payload.id ? { ...item, quantity: item.quantity - 1 } : item ), };2 Answers2
Instead of
quantity: item.quantity - 1you will need
quantity: Math.max(item.quantity - 1, 0)and have a
visibility={state.isPositive}while maintainingisPositive whenever the quantity changes.
Sign up to request clarification or add additional context in comments.
Comments
- Search the cart for the item you are adjusting the quantity of
- If the quantity dips below 1, don't include it in the new cart array value
case 'REMOVE_FROM_CART': { // Search for cart item to update const item = state.cart.find(item => item.id === action.payload.id); if (item) { // Last item, remove from cart if (item.quantity <= 1) { return { ...state, cart: state.cart.filter(item => item.id !== action.payload.id); }; } // More than 1 item, update item quantity return { ...state, cart: state.cart.map(item => item.id === action.payload.id ? { ...item, quantity: item.quantity - 1 } : item ), }; } // Item not in cart, don't update anything return state;}Comments
Explore related questions
See similar questions with these tags.


