Jason Strimpel
Jason Strimpel

Reputation: 15466

Updating Chartjs with new data

My goal is to update my chart with new data from the server. Here's my code:

(function () {
    'use strict';

    let color = Chart.helpers.color;
    window.chartColors = {
        red: 'rgb(255, 99, 132)',
        orange: 'rgb(255, 159, 64)',
        yellow: 'rgb(255, 205, 86)',
        green: 'rgb(75, 192, 192)',
        blue: 'rgb(54, 162, 235)',
        purple: 'rgb(153, 102, 255)',
        grey: 'rgb(201, 203, 207)'
    };

    let timeAxis = [{
        type: 'time',
    }];

    let percentAxis = [{
        ticks: {
            beginAtZero: false,
            callback: function(value) {
                return Math.round(value * 1000) / 10 + '%';
            }
        }
    }];

    let buildChartObject = function (ctx, type, xAxes, yAxes) {
        return new Chart(ctx, {
            type: type,
            data: null,
            options: {
                responsive: true,
                title: {
                    display: true,
                    fontStyle: 'normal',
                    padding: 10,
                    fontSize: 12

                },
                scales: {
                    xAxes: xAxes,
                    yAxes: yAxes
                },
                legend: {
                    display: false
                }
            }
        });
    };

    let loadChartData = function (endpoint, chart, params) {
        $.ajax({
            url: '/api/v1/' + endpoint,
            method: 'GET',
            dataType: 'json',
            params: params,
            success: function (d) {
                let bgColors = null, bdColors = null;
                if (chart.config.type === 'line') {
                    bgColors = color(window.chartColors.blue).alpha(0.5).rgbString();
                    bdColors = window.chartColors.blue;
                } else {
                    bgColors = d.data.map(
                        (value) => value < 0 ? color(window.chartColors.red).alpha(0.5).rgbString() :
                            color(window.chartColors.green).alpha(0.5).rgbString()
                    );
                    bdColors = d.data.map(
                        (value) => value < 0 ? window.chartColors.red : window.chartColors.green
                    );
                }
                if (chart.options.scales.xAxes[0].type === 'time') {
                    let dateUnits = {
                        daily: 'day',
                        weekly: 'week',
                        monthly: 'month',
                        yearly: 'year'
                    };
                    chart.options.scales.xAxes[0].time.unit = dateUnits[d.params.convertTo];
                }
                chart.options.title.text = d.name;
                chart.data.labels = d.index;
                chart.data.datasets[0] = {
                    backgroundColor: bgColors,
                    borderColor: bdColors,
                    borderWidth: 1,
                    data: d.data
                };
                chart.update();
            }
        });
    };

    let loadCharts = function () {
        let params = {
            convertTo: $('#convert-to').val()
        }
        let returnsChart = buildChartObject($('#chart'), 'bar', timeAxis, percentAxis);
        loadChartData('endpoint', returnsChart, params);
    }

    loadCharts();

    $('#convert-to').on('change', function() {
        loadCharts();
    });

}());

The initial call to loadCharts() correctly populates the chart. However when when the #convert-to event is triggered, the loadCharts reloads the data but I have this flickering effect of both charts drawn on the same canvas. This is not a bug or a related issue, rather a canvas drawing one.

Have a look here: https://www.dropbox.com/s/9onofdazkvp9uas/clip.mov?dl=0

I've read countless threads on this and it seems like chart.update() should solve the issue. From the docs: "[update()] triggers an update of the chart. This can be safely called after updating the data object. This will update all scales, legends, and then re-render the chart."

What am I doing wrong?

Upvotes: 0

Views: 340

Answers (1)

Daniel W Strimpel
Daniel W Strimpel

Reputation: 8470

You don't need to call buildChartObject(...) again when you are trying to just update the data for the chart. If you held onto a reference of the chart you would be fine to skip that call. Doing this will allow Chart.js to just update the chart when you call chart.update() instead of creating a new chart and then updating it.

...

let returnsChart = buildChartObject($('#chart'), 'bar', timeAxis, percentAxis);

let loadCharts = function () {
    let params = {
        convertTo: $('#convert-to').val()
    };
    loadChartData('endpoint', returnsChart, params);
}

loadCharts();

$('#convert-to').on('change', function() {
    loadCharts();
});

...

Upvotes: 1

Related Questions