[Chartjs]-Chart.js β€” using update() with time scale datasets

1πŸ‘

βœ…

The short answer: I saved the original chart as an object variable upon which I can call destroy(). After calling destroy(), I render a new chart to the same object variable.

The long answer (code samples, pulled from ES6 source):

updateTimeScaleChart() {
    this.timeScaleChart.destroy()
    this.drawTimeScaleChart()
},

drawTimeScaleChart() {
    this.timeScaleChart = new Chart($('#timeScaleChart'), {
        type: 'line',
        data: this.prepareTimeScaleChartData(),
        options: {
            aspectRatio: 1.25,
            title: {
                display: true,
                text: 'Measured over Time'
            },
            scales: {
                xAxes: [{
                    type: 'time',
                    scaleLabel: {
                        display: true,
                        labelString: 'Date'
                    }
                }]
            }
        }
    });
},

this.drawTimeScaleChart() is called when the my component is initially rendered with blank data while it waits for the JSON API data to be retrieved.

this.prepareTimeScaleChartData() is a method that formats my JSON API response into the expected ChartJS data structure.

From there, it’s just a matter of triggering updateTimeScaleChart() for appropriate events.

Leave a comment