[Chartjs]-ChartJs with try catch

1👍

You can use the static method getChart to check if a chart with that context already exists, if it does you get that chart instance which you can destroy:

catch (error) {
  if (typeof json_data !== 'undefined') {
    let chart = Chart.getChart('canvaschartjs');
    if (typeof chart !== 'undefined') {
      chart.destroy()
    }
    alert(json_data.message);
  }
}

Live example:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {}
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
let myChart = new Chart(ctx, options);

let chart = Chart.getChart('chartJSContainer');
if (typeof chart !== 'undefined') {
  chart.destroy() // Does not show anything because of this line, comment it out to show again
}
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

Leave a comment