ARTICLE AD BOX
React state updates are asynchronous. When you call navigate right after setCart, the cart variable still contains the old state, so Products Appears empty.
Compute the new cart first and use it for both setCart and navigate:
function addToCart(item) { const newCart = { ...cart, products: { ...cart.products, [item.id]: (cart.products[item.id] ?? 0) + 1 } }; setCart(newCart); navigate("/user-homepage/cart", { state: newCart }); }This works because Navigate now receives the updated cart instead of the Previous state.
3 Comments
Your issue is happening because React state updates are asynchronous, and you are navigating immediately after calling setCart. At that moment the state may not yet contain the updated products object, which is why you're seeing an empty object.
Also, the products object should be updated immutably and you should avoid relying on the current cart state right after calling setCart.
A safer implementation would look like this:
function addToCart(item) { setCart(prev => { const updatedProducts = { ...prev.products, [item.id]: (prev.products[item.id] || 0) + 1 }; const updatedCart = { ...prev, products: updatedProducts }; return updatedCart; }); }If you need to navigate to the cart page, it is better to trigger navigation after the state is updated (for example using useEffect or passing the item directly).
Example:
useEffect(() => { if (Object.keys(cart.products).length > 0) { navigate("/user-homepage/cart", { state: cart }); } }, [cart]);This ensures:
State updates remain immutable
products correctly stores item counts
Navigation happens after React updates the state
1 Comment
Please follow the policies regarding content generated by generative artificial intelligence. Here is the policy if you need it: stackoverflow.com/help/gen-ai-policy
2026-03-11T07:28:27.187Z+00:00
Explore related questions
See similar questions with these tags.

