[Chartjs]-Trying to update the inputted data in my Chart.JS graph without having to reset the whole page

1👍

Add Data and Update Data

  1. I had created one function that can used for both create and update the chart data, Use this approach to update your chart data dynamically.

  2. Also You can
    add your own fetch logic inside here

Just ignore the cross orgin script error

document.getElementById('add').onclick = function(){
  const data = [{ 
        data: [86,114,106,106,107,111,133,221,783,2478],
        label: "Africa",
        borderColor: "#3e95cd",
        fill: false
      }, { 
        data: [282,350,411,502,635,809,947,1402,3700,5267],
        label: "Asia",
        borderColor: "#8e5ea2",
        fill: false
      }
    ];
    CreateChart(data);
};
document.getElementById('update').onclick = function(){
  const newdata = 
    [
  { 
        data: [168,170,178,190,203,276,408,547,675,734],
        label: "Europe",
        borderColor: "#3cba9f",
        fill: false
      }, { 
        data: [40,20,10,16,24,38,74,167,508,784],
        label: "Latin America",
        borderColor: "#e8c3b9",
        fill: false
      }, { 
        data: [6,3,2,2,7,26,82,172,312,433],
        label: "North America",
        borderColor: "#c45850",
        fill: false
      }
  ];// array of new Data
  CreateChart(newdata);
};

let chart;

function CreateChart(data){
  if(!chart){
  chart = new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: [1500,1600,1700,1750,1800,1850,1900,1950,1999,2050],
    datasets: data
  },
  options: {
    title: {
      display: true,
      text: 'World population per region (in millions)'
    }
  }
});
}else{
  
  chart.data.datasets = data

  chart.update();
}

}
main{
  height:500px;
}
.result{
  padding:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>


<main>
<div>
  <button id='add'>Add Data </button>
  <button id='update'>Update Data </button>
</div>


<div class='result'>
  <canvas id="line-chart" width="100" height="50"></canvas>
</div>

</main>

Leave a comment