codeinprogress
codeinprogress

Reputation: 3501

Chart js old chart data not clearing

This question has been asked many times and I went through most of them but non of them helped me finding a solution.

I am generating couple of bar charts using a for loop as a part of reporting functionality.

I am using node.js with Express Handlebars.

My page looks like:

<div class="row report-charts">
    <div class="col-md-12">
    {{#buildings}}
        <div class="col-md-6">
           <h4>{{Name}}</h4>
           <canvas id="{{idBuildings}}" width="200" height="80"></canvas>
        </div>
    {{/buildings}}
    </div>
</div>

My js code looks like:

$('.case-report-btn').click(function(){

        $.ajax({
            type: 'post',
            url: '/reports/cases/filter',
            data : {
                StartDate : $('.start-ms-time-hidden').val(),
                EndDate : $('.end-ms-time-hidden').val(),
                ReportKey : $('.cases-filter-type').val()
            },
            dataType: 'json',
            success: function(res) {
                $('.report-charts').show();
                for(key in res) {
                    var innerObj = res[key]; //gives the inner obj
                    var ctx = document.getElementById(key); //the idBuildings
                    var labels = [];
                    var data = [];
                    var buildingName = innerObj.Name;
                    for(innerKey in innerObj) {
                        if(innerKey != 'Name' && innerKey != 'Total') {
                            labels.push(innerKey);
                            data.push(innerObj[innerKey]);
                        }
                    }

                    var options = {
                        type: 'bar',
                        data: {
                            labels: labels,
                            datasets: [{
                                label: buildingName,
                                data: data,
                                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                                borderColor: 'rgba(255,99,132,1)',
                                borderWidth: 1
                            }]
                        },
                        options: {
                            scales: {
                                yAxes: [{
                                    ticks: {
                                        beginAtZero:true,
                                        fixedStepSize: 1
                                    }
                                }]
                            }
                        }
                    }
                    var myChart = new Chart(ctx, options);
                }
                $('#pleaseWaitDialog').modal('hide');
            },
            error: function(err) {
                $('#pleaseWaitDialog').modal('hide');
                bootbox.alert('Error: ' + err);
            }
        });
    });

So basically, I am using for loop to generate multiple charts on the page. Inside the loop I declared the chart variable, every time I change the report parameters and hit the button, the new chart is generated. But when I hover over it, the old one still shows up.

Now I am not sure where I should be putting the myChart.destroy() or myChart.clear() methods. I also tried moving the myChart declaration outside the for loop but it didn't help either.

Any suggestions on how to handle this?

Upvotes: 1

Views: 10546

Answers (1)

piterio
piterio

Reputation: 810

I think there are a few ways to do it. You can update your chart data if the chart already exist. Here two functions you can use:

function removeData(chart) {
    chart.data.labels.pop();
    chart.data.datasets.forEach((dataset) => {
        dataset.data.pop();
    });
    chart.update();
}

function addData(chart, label, data) {
    chart.data.labels.push(label);
    chart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
    });
    chart.update();
}

First you have to remove all your data and then add the new data.

If you want to destroy the chart and create it again you have to save your variable as global. To do this you have yo declare your variable like window.myChart and then before create the new chart, something like this:

if (window.myChart) window.myChart.destroy();
window.myChart = new Chart(ctx, options);

Another way you can try is removing your canvas and creating another one. Something like this:

$('#your_canvas').remove();
$('#your_canvas_father').append('<canvas id="your_canvas"></canvas>');

Upvotes: 8

Related Questions