Home > Back-end >  Remove item from shopping cart react js
Remove item from shopping cart react js

Time:01-24

I working on adding/removing items to a shopping cart in my react js project after I add items to the cart I add "-" and " " buttons that on click should decrease/increase item quantity. I've managed to make the add-to-cart, increase work but I can't figure out how to delete the item from the cart when the quantity becomes 0. This is my code so far:

const [items, setItems] = useState([]);

const handleDecrease = (id) => {
    setItems((prevState) =>
      prevState.map(
        (item) =>
          item.id === id
            ? item.qty !== 1
              ? { ...item, qty: item.qty - 1 }
              : item.id !== id
            : item // !id
      )
    );
  };

{items?.map((item) => {
            return (
              <div
                key={item.id}
              >
                <div onClick={() => handleDecrease(item.id)}>-</div>
                <div>{item.title}</div>
                <div> ${item.price * item.qty}</div>
                <div>{item.qty}</div>
              
              </div>
            );
          })}

In my handleDecrease function, I check if the item quantity is !==1, then I decrease the quantity by 1; if the quantity is 1 and "-" is clicked again, I want to remove the item entirely from the items array, but my code only adds false to the items array. How can I remove the item?

CodePudding user response:

So what you want then is for when the user hits decrease:

If the (current) items object property qty’s value is greater than one, decrease the (current) items object property qty’s value by one. Else delete the item object all together Or better yet delete an item object who has an id property value that matches the (current) item objects property id’s value from an array of items.

CodePudding user response:

There are multiple ways to solve this problem, but the simplest is using the helping array:

const handleDecrease = (id) => {
  const newItems = [];

  items.map((item) => {
    if (item.id === id) {
      item.qty !== 1 && newItems.push({ ...item, qty: item.qty - 1 });
    } else {
      newItems.push(item);
    }
  });

  setItems(newItems);
};

CodePudding user response:

In addition to using map you can use the filter method. That way you can simplify the map logic up to only decrease the quantity then run a filter that will look for any item with quantity at 0 and remove it from the array. You can chain these together like so.

 const handleDecrease = (id) => {
            setItems((prevState) =>
                prevState.map(item => item.id === id ? 
                   ({...item, qty: item.qty - 1}) 
                : item
).filter(item => {
              return item.id === id ?
                       item.qty > 0
                     : true
                    }
                )
            )
            ;
        };

CodePudding user response:

const handleDecrease = (id) => {
  setItems((prevState) => {
    const updatedState = { ...prevState };
    const indexOf = updatedState.findIndex((elm) => elm.id === id);
    if (indexOf > -1) {
      updatedState[indexOf].qty > 0
        ? (updatedState[indexOf].qty -= 1)
        : updatedState.splice(indexOf, 1);
    }
    return updatedState;
  });
};
  • Related