0

I am trying to manage a simple shopping cart of products. The products are stored on the state as an array called items

export const state = () => ({
  cart: {
    items: [],
  }
})

If a product is already been added to the cart, and someone tries to add it again, I'm trying to update the quantity field

addItem(state, product) {
  let cartProduct = state.cart.items.find((item, index) => {
    return item.id === product.id
  })
  cartProduct.quantity++;
});

This isn't working for me as it's not updating the state. Does anyone know the trick?

1 Answer 1

2

It's reactivity issue. You can make deep copy of cart to make store reactive:

   addItem(state, product) {
      let cartProduct = state.cart.items.find((item, index) => {
        return item.id === product.id
      })
      cartProduct.quantity++;
      state.cart = JSON.parse(JSON.stringify(state.cart))
    });

Another option is using Vue.set

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any benefit in using .find(..) to change the value of the object instead of using state.cart.map(..) (with if(item.id == product.id) ...) to change the cart directly?
state.cart.map might be better. Then you don't need to do JSON.parse(JSON.stringify())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.