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.