How to Update chart in react-chartjs-2?

user8562024 picture user8562024 · Sep 5, 2017 · Viewed 17.4k times · Source

I call the update() function, but it does not work.

TypeError: line.update is not a function.

Why is update() not a function?

I have seen this example on http://jsfiddle.net/zpnx8ppb/26/ where the update function does work

Here is my code:

import React, { Component } from 'react';
import { Line } from 'react-chartjs-2';
import Chart from 'chart.js';

const line = {
    labels: [],
    datasets: [
       {
          label: 'My First dataset',
          fill: false,
          data: []
       }
    ]
};

setInterval(function(){
    line.labels.push(Math.floor(Math.random() * 100));
    line.datasets[0].data.push(Math.floor(Math.random() * 100));
    line.update();
}, 5000);

class LineChart extends Component {
    render() {
        return (
            <div className="chart">
                <Line
                    data={this.state}
                    height={5}
                    width={20}
                />
            </div>          
        )
    }
}

export default LineChart;

Answer

Dhruv Verma picture Dhruv Verma · May 8, 2019

So according to https://www.npmjs.com/package/react-chartjs-2

One can access the chart reference using a ref such as

chartReference = {};

componentDidMount() {
  console.log(this.chartReference); // returns a Chart.js instance reference
}

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

So what you could do is put a ref in your Chart and access it wherever you like.

<Line
     data={this.state}
     height={5}
     width={20}
     ref = {(reference) => this.reference = reference}
/>

In the method you wish to cause the update you could access this reference and it's chartInstance and call the update function on this instance.

let lineChart = this.reference.chartInstance
lineChart.update();