Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused. chat.JS

Viewed 10166

I have the data already for the chart, I need to not get the warning in the chart. need not destroy the chart. with out destroying the the chart the date to be updated. i used myChart(update); but this will not work is there any other way to solve the above error.

const TapsGraphCard = (props: any) => {
  var table = "myChart";
  var myChart = new Chart(table, {
    type: "bar",
    data: {
      labels: [
        "Day 1",
        "Day 2",
        "Day 3",
        "Day 4",
        "Day 5",
        "Day 6",
        "Day 7",
        "Day 8",
        "Day 9",
        "Day 10",
      ],
      datasets: [
        {
          label: "no.of Taps",
          data: [32, 256, 144, 168, 248, 96, 144, 168, 40, 144],
        },
      ],
    },

    options: {
      
      scales: {
        x: {

          display: false,
          grid: {
            display: false
          }
        },
        y: {

          display: false, 
          grid: {
            display: false
          }
        }
      },
    }
  });

  return (
    <div className="insights-container p-3">
      <div className="blue-heading">No. of Taps</div>
      <div className="description">Last 10 days</div>{" "}
      <>
      <div id="chartReport">
        <canvas id="myChart"></canvas>
        </div>
      </>
    </div>
  );
};

3 Answers

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.

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

Related