Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating count in dictionary inside array in useState

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading