[Vuejs]-Array push replace old data by new one

4👍

Your problem exists because you are having one shopping cart with each ProductCard component.

In pseudocode what you are doing is:

1. render each ProductCard
2. click on the "add cart" button
3. add the product to the cart of this specific `ProductCard` component
4. use the event bus to emit this new shopping cart (therefore replacing the old one)

You should reconsider your code to only emit the product that was added. Your application only has one shopping cart. It doesn’t have n shopping carts, therefore you only need one instance of the shopping cart.

A solution to your problem (please, feel free to change it to your needs) could be something like this:

ProductCard

<template>...</template>
<script>
export default {
  ...,
  methods: {
    addToCart(product) {
            EventBus.$emit('cartContents', product)
        }
  }
}
</script>

Then we would handle this emit event by following this simple pseudo-code:

1. receive event
2. check if this product is already in the cart
3. if it is in cart increment its quantity
4. if it's not in the cart insert a new product in the cart with quantity 1

Translating to Javascript something like this:

const products = [];

// 1. receive event
const onProductAdded = (product) => {
  // 2. check if this product is already in cart
  const product = products.find(p => p.id === product.id);

  // 4. if its not in cart insert new product in cart with quantity 1
  if (!product) {
    //  the same as doing `products.unshift({ id: product.id, quantity: 1, "and so on to all other properties" })`
    products = [{...product, quantity: 1}, ...products];
    
    return;
  }

  // 3. if it is in cart increment its quantity
  const selectedProductIndex = products.findIndex(p => p.id === product.id);
  products[selectedProductIndex] = {...products[selectedProductIndex], quantity: products[selectedProductIndex].quantity + 1};
}

Leave a comment