I have two nearly identical functions:
This one works
function addToCart(id) {
setProductsCartNew((prevProductsCart) => [...prevProductsCart, id]);
alert("Product added to cart");
}
This one does not
function handleCheckout(id) {
setProductsCartNew((prevProductsCart) => [...prevProductsCart, id]);
navigate("/checkout");
}
useEffect:
useEffect(() => {
sessionStorage.setItem("cart", JSON.stringify(productsCartNew));
}, [productsCartNew]);
Why is that so? I do get redirected, so that part of the function works.
I have checked the value of "productsCartNew", and it does in fact get updated, it's just that it doesn't get set in the sessionStorage that is the problem.
By design the setState is asynchronous so the value will be actually updated some time in the future. Since you're navigating to a different page (/checkout) I assume you do not need to actually change state in the starting component as you need to pass it to the destination page.
The correct way of handling your logic is as follows:
Remove the useEffect and move the logic inside the handleCheckout
func:
function handleCheckout(id) {
const cartArray = [...productsCartNew, id]; // productsCartNew is the state array
sessionStorage.setItem("cart", JSON.stringify(cartArray));
navigate("/checkout");
}
In this way you're able to pass every product added to cart plus the id passed to the handle function, set the sessionStorage correctly and then navigate to the checkout page where the information from the sessionStorage is retrieved.