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

Array does not update after it is set to update (React)

const [cart, setCart] = useState([])

I’m trying to add some products to cart, it got added to local storage and does not reflect on the cart array itself;

At first, I’m checking if the product exist, if it exist, update the qty, if it doesn’t add to it. It worked for if it exist, but at the first click of the button, it does not update the cart array to the product. It is as if on first click, it does not set but on second click, it sets to qty = 1 which suppose to be qty = 2

// Add Product to cart
      const addProduct = (product) => {
        const exist = cart.find((x) => x.id === product.id);
        if (exist) {
          setCart(
            cart.map((x) => 
              x.id === product.id ? { ...exist, qty: exist.qty + 1 } : x;
            )
          );
          localStorage.setItem("cart", JSON.stringify(cart));
          // Cart is there
          console.log(cart);
        } else {
          setCart([...cart, { ...product, qty: 1 }]);
          localStorage.setItem("cart", JSON.stringify(cart));
          // Cart is empty
          console.log(localStorage.getItem("cart"));
          // Cart is also empty
          console.log(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

>Solution :

This is totally normal: infact, setCart is async and you can’t log the very last value adding a console.log just after setCart call.

You should use the useEffect hook to "listen" when cart has changed.

Something like:

const [cart, setCart] = useState([]);


useEffect(() => {
  console.log(cart); // here, for each cart change, you will print the very last value
  localStorage.setItem("cart", JSON.stringify(cart)); // if value is here, you could store it...
  console.log(localStorage.getItem("cart")); // ...and of course read it
},[cart]);


// Add Product to cart
      const addProduct = (product) => {
        const exist = cart.find((x) => x.id === product.id);
        if (exist) {
          setCart(
            cart.map((x) => 
              x.id === product.id ? { ...exist, qty: exist.qty + 1 } : x;
            )
          );
        } else {
          setCart([...cart, { ...product, qty: 1 }]);
        }
      };
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