I have implemented a cart insertion system that adds items to it based on specific rules:
Initially, I initialize an empty array for the cart items:
`let cartItems = [];`
Each item in the array is a Product object with defined properties:
{
"id": 10,
"name": "Nike Hoodie 1",
...
}
When adding a new item to the cartItems
array, I want to increment the quantity
property and set the size
property if the item already exists in the array. If the new item's productSize
differs from the existing item's productSize
, I want to add the new item with quantity: 1
.
The challenge arises when dealing with identical id
properties for different products. This causes issues when trying to update or remove items from the cartItems
array using the id
. Any suggestions on how to resolve this?
I attempted assigning a temporaryId
property with a random number for each product, but I'm unsure about its effectiveness. Here is the code snippet I came up with:
export const addItemToCart = (cartItems, cartItemToAdd, selectedSize) => {
const existingCartItem = cartItems.find(
(cartItem) => cartItem.id === cartItemToAdd.id
);
if (existingCartItem) {
if (existingCartItem.productSize === selectedSize) {
console.log('Product sizes match');
return cartItems.map((cartItem) =>
cartItem.id === cartItemToAdd.id
? {
...cartItem,
quantity: cartItem.quantity + 1,
}
: cartItem
);
} else {
console.log('Product sizes do not match');
return cartItems.map((cartItem) =>
cartItem.id === cartItemToAdd.id
? {
...cartItem,
quantity: cartItem.quantity + 1,
productSize: selectedSize,
}
: cartItem
);
}
}
let randomId = Math.floor(1000 + Math.random() * 9000);
return [
...cartItems,
{
...cartItemToAdd,
tempId: randomId,
quantity: 1,
productSize: selectedSize,
},
];
};