How to use setTimeout for removing items from cart

33 views Asked by At

My e-commerce site contains Products(view) and Cart(view) and when I add items to cart I have button "Remove". I want to set Timeout when I click Remove button, which removes the product. Remove button works only when I change the page and come back, but I want to add Timeout and to remove it immediately.

This is my logic in remove function. I add timeout here. I have removing key in object initially on false; This code is located in my store.js file (objects seen here);

export function removeFromCart(id){
    cart[id].removing = true; // Set removing flag to trigger animation
    const index = cart.findIndex(item => item === id);
    if (index !== -1) {
        setTimeout(() => {
            cart.splice(index, 1); // Remove item after animation
        }, 500); // Set the animation duration (milliseconds)
}

This is my code in CartMain.vue

<tr
  v-for="item in cartItems"
  :key="item.name"
  :class="{ 'remove-animation': item.removing }"
></tr>

And this is my style also

.remove-animation {
  transition: opacity 0.5s ease; /* Adjust the animation properties as needed */
  opacity: 0;
}
0

There are 0 answers