B
B
bormor2018-08-10 15:29:03
JavaScript
bormor, 2018-08-10 15:29:03

Vuex: why is the object not being added correctly here?

I'm learning Vuex.
The task is to add a product by id from state.products to state.cart.
When adding a product with any id, the first element is added.
For example id = 3, add product {title: 'Item 1', price: 100, id:3}

export default new Vuex.Store({
state:{
    products: [
            {title: 'Товар 1', price: 100, id:1},
            {title: 'Товар 2', price: 200, id:2},
            {title: 'Товар 3', price: 300, id:3},
            {title: 'Товар 4', price: 300, id:4},
    ],
    cartItems:[]
},
mutations:{
    addToCart(state, id){
        const productIndex = state.products.findIndex(item => item.id = id);
        let addedProduct = state.products[productIndex];

        state.cartItems.push(addedProduct);
    }
});

What could be the reason? What can help? What is worth studying?
UPD. Thank you all :) We must learn to get enough sleep at night.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-08-10
@bormor

findIndex(item => item.id = id)

Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!!!!!!
What is worth studying?

Learn more about how assignment differs from equality testing.
UPD. Why findIndex is used is not very clear - using find will make the code simpler:
addToCart(state, id) {
  state.cartItems.push(state.products.find(item => item.id === id));
},

And if, where you call the mutation from, not only the id, but the entire object is available, you can pass it to the mutation, and then you won’t need to look for anything:
addToCart(state, product) {
  state.cartItems.push(product);
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question