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

Time:03-05

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);
        }
      };

CodePudding user response:

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 }]);
        }
      };
  • Related