Change state of inner array values

Viewed 39

I am trying to massage this array I have formed into my state... [1, 2, 2, 1, 3, 3, 2, 3, 2, 1, 1, 3, 1, 1]

The state looks like this...

options: {
  title: {
    text: 'My chart',
  },
  series: [
    {
      threshold: 2,
      negativeColor: 'red',
      color: 'green',
      type: 'area',
      data: [1, 2, 3],
    },
  ],
},

I have got this far but i'm getting stuck and confused...

this.setState({ options: { ...this.state.options, data: myData } })

And various combos of.options.series[0] etc. Can someone help me finish this off.

1 Answers

You need to shallow copy the nested state. I also suggest using a functional state update so you ensure updating state from the previous state (versus the state of the render cycle the update was enqueued in).

this.setState(prevState => {
  const newSeries = [...prevState.options.series]; // <-- shallow copy array
  newSeries[0] = {
    ...newSeries[0], // <-- shallow copy element
    data: [...newSeries[0].data, ...myData]; // <-- shallow copy data & new data
  };

  return {
    ...prevState, // <-- shallow copy previous state
    options: {
      ...prevState.options, // <-- shallow copy options
      series: newSeries,
    },
  }
});

The reason for all the shallow copying is that React uses shallow reference equality checks as part of the reconciliation process. In other words, it assumes if the state or prop value is still the same reference in memory that the value hasn't changed and that part of a component tree may not need to be rerendered. This is why not mutating the state and props is an important detail in React.

Related