Hi guys,
I’m working on a typical e-commerce platform and I’ve created a function to add items to the cart whenever a user clicks on a button. Once an item is added, the button gets disabled and the text changes from ‘add to cart’ to ‘in cart’.
The problem that I’m facing is that sometimes when I click on a button, it doesn’t get disabled and also the text doesn’t get updated but the item is still added to the cart. It happens sporadically and completely randomly. I tried to search for some patterns but I can’t find any and have no idea what could be a reason of that. Any ideas? Basically it looks like once in a while the function is skipping the first step on random products but I have no idea how it happens.
The function has the following steps:
- User clicks on a button.
- The text of a button changes and the button gets disabled.
- Searches for the relevant item in a local storage and adds it to a cart.
- Updates local storage etc.
The function:
button.addEventListener("click",(event) => {
event.target.innerText = "In Cart";
event.target.disabled = true;
// get the product and also add the amount
let cartItem = {...Storage.getProduct(id), amount: 1};
// add product to the cart
cart = [...cart, cartItem];
// save the cart in the local storage
Storage.saveCart(cart)
// set cart values
this.setCartValues(cart);
// display cart item
this.addCartItem(cartItem);
// check if the cart is empty or not
this.bagIsEmpty();
});
Thank you as usual!