Search code examples
javascriptreactjsimmutabilitymutable

How to immutable update an object given that we have to pass the same object as props?


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?


Solution

  • As mentioned in the comments, there are a few things going on:

    1. You are not updating the amounts Array reference, so React will not re-render based on this mutation.
    2. You are using Array#map to update a single property. This will update the Object reference in the amounts collection.
    3. There is no 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 })
        );
      );
    }