In nextJs I created a provider for useState, now I am able to add items to the cart, but that’s all that I can do…
cart = [{product: "product name", count:1}]
When I want to add an item to this I can do
setCart([...cart, {product:'new one', count:1}])
But I am just not able to write code that will update the count of existing items in the cart…
I don’t know how…
>Solution :
You cannot just spread the new item. You need to check the existing cart and update according.
In the React demo below, you can click the buttons to add the items to the cart.
const { useCallback, useEffect, useState } = React;
const fetchProducts = Promise.resolve([
{ name: 'Apple' }, { name: 'Banana' }, { name: 'Pear' }
]);
const App = () => {
const [products, setProducts] = useState([]);
const [cart, setCart] = useState([]);
const addToCart = useCallback((e) => {
const product = e.target.textContent;
setCart((existingCart) => {
const cartCopy = structuredClone(existingCart);
let existing = cartCopy.find((item) => item.product === product);
if (existing) {
existing.count += 1;
} else {
cartCopy.push({ product, count: 1 });
}
return cartCopy;
});
}, []);
useEffect(() => {
fetchProducts.then(setProducts);
}, []);
return (
<div>
<h2>Products</h2>
{products.map(({ name }) => (
<button key={name} onClick={addToCart}>{name}</button>
))}
<h2>Cart</h2>
<ul>
{cart.map(({ product, count }) => (
<li key={product}>{`${product} ×${count}`}</li>
))}
</ul>
</div>
);
};
ReactDOM
.createRoot(document.getElementById("root"))
.render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>