I’m trying to store each of the product’s id in the cartItems, however, the ID is being saved as an array as demonstrated in the picture below. Instead of being saved like this id: "aRLMZkiSU7T0lcsPCSsV"
How do I fix this?
code sandbox: https://codesandbox.io/s/add-to-cart-jsd9fd?file=/src/App.js:0-2587
Below are the 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:
Remove the spread operator from Id.
else {
setCartItems([
...cartItems,
{ id, name, size, cat, color, quantity: 1 }
]);
}