Cart functionality in reactjs

14 hours ago 2
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.

Sekhar Chaudhary's user avatar

3 Comments

Thanks for the reminder. I didn’t use AI to write this answer. I wrote it based on my understanding and tested the code locally before posting. If anything in the answer looks incorrect or could be improved, please let me know and I’ll be happy to update it.

2026-03-11T07:43:08.307Z+00:00

My friend... That comment is literally AI-generated as well...

2026-03-11T07:46:53.437Z+00:00

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

deependra Shilpi's user avatar

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article