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.

2 Answers 2

1

Try this

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

use like this

this.setState({
  ...this.state,
  graphData: [...this.state.graphData, {x:1,y:1}]
})
Sign up to request clarification or add additional context in comments.

Comments

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
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.