Reputation: 35
When I add the product to the cart and then I add another one, then if I try to add the first one again it doesn't increase only the quantity but it creates a new object for this product; how can I fix it
switch (action.type) {
case actionTypes.ADD_TO_CART:
const product = state.products.find((p) => p.id === action.payload.id);
const inCart = state.cart.find((item) =>
item?.product.id === action.payload.id ? true : false
);
if (inCart) {
let check = false;
state.cart.map((item, key) => {
if (
item.product.id === action.payload.id &&
item.setVar === action.payload.setVar
) {
state.cart[key].quantity++;
check = true;
}
});
if (!check) {
const newItem = {
product: product,
setVar: action.payload.setVar,
quantity: 1,
};
state.cart.push(newItem);
}
} else {
const newItem = {
product: product,
setVar: action.payload.setVar,
quantity: 1,
};
state.cart.push(newItem);
}
return {
...state,
};
}
Upvotes: 1
Views: 270
Reputation: 35
item.product.id === action.payload.id && JSON.stringify(item.setVar) === JSON.stringify(action.payload.setVar)
Upvotes: 1