I have an object amounts that gets updated on button clicks. Ans i pass that object as a prop to another component. What i am doing right now is updating object in mutable way on button click event.
onClick = e => {
amounts.map(
amount => (amount.tax = taxes ? 500 : 0)
);
}
<Display amounts={amounts} />
How can i update amounts in an immutable way?
As mentioned in the comments, there are a few things going on:
amounts Array reference, so React will not re-render based on this mutation.Array#map to update a single property. This will update the Object reference in the amounts collection.setAmounts or anything similar in order to update the value of the amount property in a parent component.Assuming you are using useState in the <Display />s parent component, you will have to pass the setAmounts function to the <Display /> component using props.
<Display amounts={amounts} setAmounts={setAmounts} />
onClick = e => {
setAmounts(
amounts.map(
amount => ({ ...amount, tax: taxes ? 500 : 0 })
);
);
}