3

I am newbie to react and i am trying to learn useReducer and useContext. What i am trying to do is add the product to the cart and adding it to the context variable by using setContext,

const [context, setContext] = useContext(Context)
const [cart, dispatch] = useReducer(reducer, [])

but the setContext(cart) doesnt updates the context on the first time when i click "ADD TO CART" button. The context variable returns an empty array, but the cart is updated and renders with the product which i added. But during the next time when i click "ADD TO CART" it updates the context variable. I am not able to find the reason why it is. Could anyone help me understand why and how to rectify it. Here is the codesandbox which i am using to work and study this. Please make changes if you find anything wrong. Codesandbox

  • You might want to elaborate a bit on this post. When I play with your sandbox and I add items to the cart in /categories the gui changes and appears to be adding the items to the cart. However, when I go back to "/" and then go back into "/categories" the cart is empty when I expect it to still have items in it. Is that the bug you are trying to resolve? – Luke Apr 30 '21 at 18:08
  • Hi Luke, yes you are right. also i wanted the items added to be viewed from /categories to /. So i am trying to add the product using setContext(cart) in Category.js in line 30, when i click the ADD TO CART button, the first time the context variable is empty, the second time it updates with the cart object. My query is why it is not updating the first time. – praveen kumar May 01 '21 at 00:04
  • It is better to use useReducer instead of useState for storing the globalState. Because when you update an object with useState it does not merge with the existing Object. it replaces it. – Ravi Theja May 01 '21 at 04:57

0 Answers0