javascriptarraysreactjsreact-vis

How to update state of 2D array with N objects inside in React?


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.


Solution

  • Try this

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

    use like this

    this.setState({
      ...this.state,
      graphData: [...this.state.graphData, {x:1,y:1}]
    })