javascriptreactjsreact-chartjs

How to Update chart in react-chartjs-2?


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;

Solution

  • You need to update the chart, line is just a config setting on the chart, this update needs to flow back to the handler

    To set you on the right path, here is an example of what I mean

    var config = {};
    
    class Chart extends Component {
        constructor() {
            super();
            this.ctx = document.getElementById(this._rootNodeID).getContext("2d");
            this.chart = new Chart(ctx, config);
    
        }
    
    
        changeHandler(value) {
            this.chart.update();
        }
    
        render() {
            return (
                <canvas id={this._rootNodeID}>
                    <LineChart value={this.state.value} 
                               config={this.config} 
                               onChange={this.changeHandler}/>
                </canvas>
            );
        }
    }
    
    
    const line = {
        labels: [],
        datasets: [
            {
                label: 'My First dataset',
                fill: false,
                data: []
            }
        ]
    };
    
    
    
    class LineChart extends Component {
    
        constructor(props) {
            super(props);
    
            this.props.config = line;
            setInterval(function(){
                this.props.config.labels.push(Math.floor(Math.random() * 100));
                this.props.config.datasets[0].data.push(Math.floor(Math.random() * 100));
                this.props.changeHandler();
            }, 5000);
    
        }
    
    
        render() {
            return (
                <div className="chart">
                    <Line
                        data={this.state}
                        height={5}
                        width={20}
                    />
                </div>
            )
        }
    }
    
    export default Chart;
    export default LineChart;