Chartjs-I cannot update my chart ( in react-chartjs-2 )

0👍

function has its own this context so you either have to store the this context in a local variable before the setInterval or use an arrow function instead of function

setInterval(() => {
       this.props.changeHandler();
    }, 500); 

0👍

First you need to obtain a reference to the Chart.js instance.

constructor() {
  ... 
  this.chartReference = React.createRef(); 
  ...
}

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

From this reference, you can obtain the chart instance, update its data and finally invoke chart.update().

setInterval(() => {
  const chart = this.chartReference.current.chartInstance;
  chart.data.datasets[0].data = [<the new data>];
  chart.update();
}, 2000); 

Please take a look at this StackBlitz and see how it works.

Leave a comment