It appears that there are a couple of issues that need to be addressed.
- The
product
parameter in your find
callback function is overshadowing the product
parameter from the ADD_ITEM
function. To avoid confusion, let's rename it to p
.
- Within the
find
callback, you need to verify if the productID
of p
matches the provided product
's ID.
- It seems like you intend to simply add the entire
product
object to the storeCart
, rather than pushing each individual property separately.
- Be sure to increment the
productQuantity
property on added
, as it references the existing item in the state.
export function ADD_ITEM(state, product) {
const added = state.storeCart.find(p => p.productID === product.productID);
if (!added) {
state.storeCart.push(product);
} else {
added.productQuantity++;
}
}
To illustrate the functionality of this code, here is a basic example:
function ADD_ITEM(state, product) {
const added = state.storeCart.find(p => p.productID === product.productID);
if (!added) {
state.storeCart.push({...product});
} else {
added.productQuantity++;
}
}
const state = {
storeCart: []
}
const hat = { productID: 1, name: "hat", productQuantity: 1 };
const jacket = { productID: 2, name: "jacket", productQuantity: 1 };
const shoes = { productID: 3, name: "shoes", productQuantity: 1 };
ADD_ITEM(state, hat);
ADD_ITEM(state, jacket);
ADD_ITEM(state, shoes);
ADD_ITEM(state, jacket);
console.log(state);