Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-chartjs-2 not updating graph when state updates

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.

like image 874
Bryan Licata Avatar asked Mar 16 '18 09:03

Bryan Licata


2 Answers

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.

like image 177
Tomasz Mularczyk Avatar answered Nov 11 '22 21:11

Tomasz Mularczyk


Check this link. You can see that he binds the function to the component.

https://codepen.io/gaearon/pen/xEmzGg?editors=0010

// This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
like image 1
Janick Fischer Avatar answered Nov 11 '22 20:11

Janick Fischer