Skip to content
Advertisement

Update a redux array of object but not re-render the component

PROBLEM STATEMENT

I am trying to modify a array of objects that is stored in redux store. After updating from a component it doesn’t re-render the component.
Basically, I take a redux-state which is a array of objects using mapStateToProps. Then, update a object in this array from a react component. I expect when the array is manipulated the component will re-render with updated array. But, unfortunately when I update the object of this array, my component can’t detect the changes.

REDUX STATE

JavaScript

REACT COMPONENT

Here, increaseItem function just update the quantity of a item.
Note : When increaseItem function called, redux-dev-tools shows the changes.

JavaScript

How can I resolve this issue ????

Advertisement

Answer

food.quantity++ is a mutation of the Redux state. This will cause the value in Redux to change, but the component will not re-render because you mutated the data rather than updating it properly.

As far as React is concerned, basket hasn’t changed since the array contains the same items as before. You mutated one of those items such that the quantity is different, but React doesn’t know that. That’s why you had to use JSON.stringify(basket) in your useEffect dependencies instead of basket.


You cannot call food.quantity++ in your reducer either, unless you are using a helper library like Redux Toolkit. Every object that you change must be replaced with a copied version. A non-mutating reducer should look like this:

JavaScript

With Redux Toolkit, it’s a lot simpler.

JavaScript
JavaScript

Code Sandbox Demo

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