[Chartjs]-Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused. chart.JS

11๐Ÿ‘

The canvas is not destroyed when ever the component is unmounted and the ref still holds a previous value. Try this instead:

const TapsGraphCard = (props: any) => {

  useEffect(() => {
  var myChart = new Chart(table, config);

  // when component unmounts
  return () => {
      myChart.destroy()
    }
  }, [])
  
  //  ...rest of your code
};

The cleanup makes sure that when the component is unmounted the canvas is destroyed and a new instance is created once the component is mounted again.

6๐Ÿ‘

if using react with typescript import this

import "chart.js/auto";

this will be fine for eslint @typescript

3๐Ÿ‘

var myChart = null;

const TapsGraphCard = (props: any) => 
{
    var table = "myChart";
    if(myChart){
        myChart.clear();
        myChart.destroy();
    }
    myChart = new Chart(table, {
        //rest of your code        
    });
}

2๐Ÿ‘

If youโ€™re using react-chartjs-2 make sure to add this import: import { Chart as ChartJS } from 'chart.js/auto'
This fixed the issue for me.
Refer to this answer: https://stackoverflow.com/a/70142666/6022510

0๐Ÿ‘

When you are updating the chart make sure to call the this.chart.destroy() function first, This fixed the issue for me.

Leave a comment