[Chartjs]-Handling data over lapping in chart.js

1👍

Every time you update it, you’re sort of like, creating a new chart over it. What you need to do is to destroy the chart before updating it.
myChart.destroy()

I updated your javascript code:

 var chartList = [5,6];
 var myChart;

   function chart(){
    var ctx = document.getElementById("myChart").getContext('2d');
     if (myChart != undefined && typeof myChart == 'object' && typeof myChart.destroy == 'function') myChart.destroy()    
     myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ["Red", "Blue"],
                datasets: [{
                    label: '# of Votes',
                    data: chartList,
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                    ],
                    borderColor: [
                        'rgba(255,99,132,1)',
                        'rgba(54, 162, 235, 1)',
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        }
                    }]
                }
            }
        });

   }

   chart();

  function addData(){
             var i = 4;
             var o = 8;

             chartList = [];
                chartList.push(i);
                chartList.push(o);
                chart();


        }

Leave a comment