Skip to content
Advertisement

Unable to increment or decrement my quantity value React JS

So I am building a shopping cart, I am done with most of my code but when I try to increment or decrement the value of a product quantity from cart it just fetches me the value of current quantity it doesn’t get updated. I am unable to understand where I am making the mistake.

This is my cart.js file

JavaScript

Advertisement

Answer

Issue

The issue appears to be state mutation. When you find a matching product and set the quantity property you are mutating the product object and since object is still shallow reference equal React bails on rerendering it. This is why you see stale UI.

JavaScript

Additionally, the Array.prototype.find method can potentially return undefined if a matching product item isn’t found, and if this happens your code will throw an error when it attempts to access quantity of undefined.

You’ve also some odd logic around incrementing/decrementing the quantity by 1. Just add/subtract 1 from the quantity.

Solution

Shallow copy all state that is being updated.

JavaScript

Fix the button callbacks. Just let the amount be what is added to the quantity.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement