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