0

I'm working with chartjs and trying to update my initial state with an API call which looks like:

this.state = {
      data: {
        labels: [], //<-- SET THIS STATE
        datasets: [{
            fill: 'false',
            lineTension: 0,
            label: 'Price in USD',
            data: [], //<-- SET THIS STATE
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    }
}

I need to setState for labels - which I have done already. But got lost and confused as to also setState for code below at the same time.

data: {
        labels: [],
        datasets: [{
            fill: 'false',
            lineTension: 0,
            label: 'Price in USD',
            data: [], <------THISSSS

Here's what I did to set my labels state

let labels = this.state.data.labels
          labels = timeData
          this.setState(({data}) => ({data: {
            ...data,
            labels: labels
          }}))

1 Answer 1

1

You are initializing labels as this.state.data.labels, which is fine, but then you change it to timeData, which I'm assuming is declared somewhere else in the code. You don't need to set labels to this.state.data.labels if you're going to assign it a new value immediately after. Also, if you want to simplify it further, you can also exclude the line labels = timeData and just use timeData in the setState call.

As for the this.setState() call, you should not be passing it a function.

To answer your question, this is how you can set the state of labels and the second data property without affecting the rest of the state:

this.setState({
    data: {
        labels: timeData,
        datasets: [{
            ...this.state.data.datasets,
            data: SOME_VALUE_HERE
        }]
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Actually it seems like setState is not carrying over unchanged values from initial State. for example the label, background colour, etc is not set in state after.
I just tested it and it worked for me. Please create a jsfiddle with your code and I will help troubleshoot.

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.