0

Before I jump on subject, I want to mention that I've already referred to questions like these, but could not figure the solution on my own.

Updating React state as a 2d array?

Let's assume this is my state object

state = {
    graphData: [
        [{x: 0, y: 0}],
    ],
};

As time increases, graphData will get bigger and might look something like this

    graphData: [
        [{x: 0, y: 0}, {x: 1, y:1}, {x:2, y:2}],
    ],

At the moment, I handle that in this manner:

  nextGraphData = this.state.graphData[0][graphDataLength] = {x: lastXAxisValue + 1, y: value};

    this.setState({
        graphData: {
            ...this.state.graphData,
            nextGraphData
        }
    });

Obviously, I get an error saying I should not mutate state directly. So, how to achieve the same without direct mutation. I tried to play around a bit, but could not figure it out.

Seinfeld
  • 433
  • 7
  • 24

2 Answers2

1

Try this

state = {
    graphData: [
        [{x: 0, y: 0}],
    ],
};

use like this

this.setState({
  ...this.state,
  graphData: [...this.state.graphData, {x:1,y:1}]
})
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
1

The error appears because of this line

nextGraphData = this.state.graphData[0][graphDataLength] = {x: lastXAxisValue + 1, y: value};

as you are trying to assign value directly to the state.graphData

what you have to do is to change it like this:

let nextGraphData = {...this.state.graphData,{x: lastXAxisValue + 1, y: value}};

this.setState({
    graphData: {
        ...nextGraphData
    }
});
ROOT
  • 11,363
  • 5
  • 30
  • 45