0

I'm new to these stuff but I am passionate about learning it. So feel free to link documentations, I would gladly look up for them. I have built a cart list component in Reactjs. I implemented addToCart and removeFromCart functions. The problem lies in removeFromCart function. I have a json file from which I get my categories and products. I have onClick declerations that change the state of the component and render the new product list for the desired category. I added a button that removes products from cart but the button only decrease the quantity of the product. I want to remove the product when its quantity drops below zero. Here is my code, I hope you could help.

 changeCategory = (category) => {
    this.setState({ currentCategory: category.categoryName });
    this.getProducts(category.id);
  };
   resetCategory = (category) => {
     this.setState({currentCategory: "",});
     this.getProducts()
   };
  getProducts = (categoryId) => {
    let url = "http://localhost:3000/products";
    if (categoryId) {
      url += "?categoryId=" + categoryId;
    }
    fetch(url)
      .then((response) => response.json())
      .then((data) => this.setState({ products: data }));
  };
  addToCart = (product) => {
    let newCart = this.state.cart;
    var addedItem = newCart.find((c) => c.product.id === product.id);
    if (addedItem) {
      addedItem.quantity += 1;
    } else {
      newCart.push({ product: product, quantity: 1 });
    }

    this.setState({ cart: newCart });
    alertify.success(product.productName + " added to the cart.,", 2);
  };

This is what the states of component looks like:

state = {
    currentCategory: "",
    products: [],
    cart: [],
  };

And lastly the problematic part:

removeFromCart = (product) => {
    let newCart = this.state.cart;
    var addedItem = newCart.find((c) => c.product.id === product.id);
    if (addedItem) {
      addedItem.quantity -= 1;
    } 
    // var zeroItem = addedItem.quantity ;
    // zeroItem = newCart.filter((a) => a.addedItem.quantity !== 0)
    // this.state.zeroItem.filter((c) => c.product.id !== product.id);
    this.setState({ cart: newCart });
    alertify.error(product.productName + " removed from the cart.", 2);
  };

Comment section was what I tried but they didn't work, obviously. How can I remove a product in a project like this when its quantity drops below zero? Thanks everyone in advance.

For those who would help: I have no problem for decreasing the quantity. I just need a way to remove that specific object it when the addedItem's quantity drops below 0.

  • Does this answer your question? [How can I remove a specific item from an array?](https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array) – Heretic Monkey Dec 31 '20 at 01:00

2 Answers2

0
removeFromCart = (product) => {
  let {cart}=this.state;
  let {quantity:currentQuantity} = cart.find(pr => pr.product ===product)
  if(currentQuantity > 1) {
    this.setState(prevState => 
      ({cart : [...prevState.cart.filter(pr => pr.product !== product), {product, quantity: currentQuantity-1} ] })) 
  }
  else { 
  this.setState(prevState => 
    ({cart : prevState.cart.filter(pr => pr.product !== product) })) 
  }
}
aligumustosun
  • 152
  • 10
  • Wow, it works thanks. One last question. The product's row change when I decreased its quantity now. Is there any way to prevent that? – Gokhan Guney Dec 31 '20 at 01:07
  • shouldComponentUpdate(nextProps, nextState) { if(nextState.cart.length === this.state.cart.length) { return false; } } – aligumustosun Dec 31 '20 at 01:11
0

You can simply use a filter to remove an item from the array.

    removeFromCart = (product) => {
        let newCart = this.state.cart;
        var addedItem = newCart.find((c) => c.product.id === product.id);
        if (addedItem && addedItem.quantity > 1) {
            addedItem.quantity -= 1;
        } else {
            newCart = newCart.filter(({ id }) => id === product.id)
        }
        // var zeroItem = addedItem.quantity ;
        // zeroItem = newCart.filter((a) => a.addedItem.quantity !== 0)
        // this.state.zeroItem.filter((c) => c.product.id !== product.id);
        this.setState({ cart: newCart });
        alertify.error(product.productName + " removed from the cart.", 2);
  };

I just edited your code a little and now it works like a charm. You can see the revised version of mine below.

 removeFromCart = (product) => {
    let newCart = this.state.cart;
    var addedItem = newCart.find((c) => c.product.id === product.id);
    if (addedItem && addedItem.quantity > 1) {
        addedItem.quantity -= 1;
    } else {
        newCart = newCart.filter((c) => c.product.id !== product.id);
        this.setState({ cart: newCart });
    }
    this.setState({ cart: newCart });
    alertify.error(product.productName + " removed from the cart.", 2);
  };
Yadab
  • 1,767
  • 1
  • 10
  • 16
  • Thanks for your reply. This works for decreasing but when a products quantity drops below zero, it wipes the entire cart. – Gokhan Guney Dec 31 '20 at 01:15