react-chartjs-2 not updating graph when state updates

Bryan Licata picture Bryan Licata · Mar 16, 2018 · Viewed 8.2k times · Source

I am creating a dashboard app that fetches data from an endpoint and uses the setState method to assign variables from the JSON returned by the endpoint to state variables. When I make a change to state, some components like 'react-svg-gauge' will update but 'react-chartjs-2' does not update.

The below code is an example of how my state changes in my actual app. This example will display the correct value of the state variables in the chrome developer console but does not update the DOM accordingly.

import React, { Component } from 'react';
import {Doughnut} from 'react-chartjs-2';

class DoughnutExample extends Component {
  state = {
    data: {
        labels: [
            'Red',
            'Green',
            'Yellow'
        ],
        datasets: [{
            data: [300, 50, 100],
            backgroundColor: [
            '#FF6384',
            '#36A2EB',
            '#FFCE56'
            ],
            hoverBackgroundColor: [
            '#FF6384',
            '#36A2EB',
            '#FFCE56'
            ]
        }]
    }
  }

  componentDidMount() {
    this.timer = setInterval(
      () => this.increment(),
      1000
    )
  }

  componentWillUnmount() {
    clearInterval(this.timer)
  }

  increment() {
    let datacopy = Object.assign({}, this.state.data)
    datacopy.datasets[0].data[0] = datacopy.datasets[0].data[0] + 10
    console.log(datacopy.datasets[0].data[0])
    this.setState({data: datacopy})
  }

  render(){
    return(
      <div>
      <Doughnut data = {this.state.data}/>
      </div>
    )
  }
}

export default DoughnutExample;

Am I using the lifecycle methods correctly? This code will update the value of the pie chart, the state variable but will not correctly render the DOM.

Answer

Tomasz Mularczyk picture Tomasz Mularczyk · Mar 16, 2018

The potential issue I see is that you try to update nested property while you mutate it. So if Doughnut is passing parts of data to other components they will not be notified that props have changed. So it is necessary to do deep clone:

increment() {
    const datasetsCopy = this.state.data.datasets.slice(0);
    const dataCopy = datasetsCopy[0].data.slice(0);
    dataCopy[0] = dataCopy[0] + 10;
    datasetsCopy[0].data = dataCopy;

    this.setState({
        data: Object.assign({}, this.state.data, {
            datasets: datasetsCopy
        })
    });
}

You may also need to bind the function like @Janick Fisher suggests.