3

I have read multiple answers to a similar question and have tried everything but nothing seems to work. When I update the data on Chartjs bar graph and hover on the graph, it keeps flickering between the old and new data.

Below is my graph component:

import React, { useRef, useEffect, useCallback, useState } from 'react';
import Chart from 'chart.js';


const BarChart = (props: BarChartProps, ref): JSX.Element => {
  const { xAxisLabels, yAxisValues, barSettings, hideLegend } = props;
  const barChartRef = useRef<HTMLCanvasElement>(null);
  let myBarChart;

  const buildChart = () => {
    const myBarChartRef = barChartRef.current.getContext("2d");
    if(myBarChart) {
      myBarChart.destroy();
    }
    myBarChart = new Chart(myBarChartRef, {
      type: 'bar',
      data: {...},
      options: {...}
    });
  }

  useEffect(() => {
    buildChart();
  }, [buildChart]);

  return (
    <div style={{width: barSettings.width}}>
      <canvas ref={barChartRef} />
    </div>
  )
}

export default BarChart;

And the data is being dynamically changed from a component outside(although I doubt this has anything to do with the problem) like so:

export const OutsideComponent = () => {
  const [ydata, setYData] = useState(getYAxisValues(barChartData));

  const updateGraph = () => {
    setYData(getYAxisValues(barChartData2));
  }

  return (
    <div>
      <button onClick={updateGraph}>Update Graph1</button>
      <BarChart
        xAxisLabels={getXAxisLabels(barChartData)}
        yAxisValues={ydata}
        barSettings={settings}
      />
    </div>
  )
};

Nothing seems to work for me. I've tried chart.destroy(), chart.update() but nothing seems to solve the problem. I've also tried changing responsiveness and any other advice that other answers have provided but nothing still.

0 Answers0