Answer the question
In order to leave comments, you need to log in
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);
}
});
Answer the question
In order to leave comments, you need to log in
findIndex(item => item.id = id)
What is worth studying?
addToCart(state, id) {
state.cartItems.push(state.products.find(item => item.id === id));
},
addToCart(state, product) {
state.cartItems.push(product);
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question