I have these products with product variations of colors. The problem is that it does not record the product’s color that I have added. For example, the shirt has 2 colors red and green, and I’ll choose red, only the red will be saved and the quantity will be updated for that product as a whole but not on the color.
This is what happens:
Codesandbox: https://codesandbox.io/s/add-to-cart-jsd9fd?file=/src/App.js:0-2599
Codes:
export default function App() {
const [cartItems, setCartItems] = useState([]);
const handleAdd = (id, name, size, cat, color) => {
console.log("add", id, name, size, cat, color);
const productExist = cartItems.find((item) => item.id === id);
if (productExist) {
setCartItems(
cartItems.map((item) =>
item.id === id
? { ...productExist, quantity: productExist.quantity 1 }
: item
)
);
} else {
setCartItems([...cartItems, { id, name, size, cat, color, quantity: 1 }]);
}
};
// const handleAdd = (item) => {
// console.log("add", item);
// };
console.log(cartItems);
return (
<div className="App">
{products.map((index) => (
<ul key={index.id}>
<li>
<b>{index.prodName}</b>
</li>
<li>Category: {index.cat}</li>
<li>Size: {index.size}</li>
{Object.entries(index.colorMap).map((color) => (
<>
{color[1] !== 0 ? (
<>
{color[0]}
<button
onClick={(e) =>
handleAdd(
index.id,
index.prodName,
index.size,
index.cat,
color[0]
)
}
>
Add to Cart
</button>
{/* <button onClick={(e) => handleAdd(index)}>Add to Cart</button> */}
</>
) : (
<>2</>
)}
<br />
</>
))}
Php {index.price}.00
</ul>
))}
<Cart cartItems={cartItems} />
</div>
);
}
CodePudding user response:
When you check if the product is already in the cart, you only check by its id
:
const productExist = cartItems.find((item) => item.id === id);
But if you want to separate the products by id
and color
then you need to check for that too:
const productExist = cartItems.find((item) => item.id === id && item.color === color);
And of course update the same comparison logic when updating the cart:
setCartItems(
cartItems.map((item) =>
(item.id === id && item.color === color) // <--- here
? { ...productExist, quantity: productExist.quantity 1 }
: item
)
);