2

I am currently working on a React-Redux based Cart app, and I am experiencing the following problem:

enter image description here

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      ),  };
Drew Reese's user avatar
Drew Reese
207k19 gold badges277 silver badges291 bronze badges
askedMay 31 at 14:46
Tom Vuma's user avatar

2 Answers2

0

Instead of

quantity: item.quantity - 1

you will need

quantity: Math.max(item.quantity - 1, 0)

and have a

visibility={state.isPositive}

while maintainingisPositive whenever the quantity changes.

answeredMay 31 at 15:46
Lajos Arpad's user avatar
Sign up to request clarification or add additional context in comments.

Comments

0
  • 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;}
answeredMay 31 at 18:33
Drew Reese's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.