I'm trying to update a chartjs using the useEffect hook.
However my react page is crashing saying:
TypeError: Cannot read property 'data' of undefined
Here is the code:
const MyChart = ({ chartData }: Props) => {
const barChartData: Chart.ChartData = {
labels: ["a", "b", "c", "d", "e", "f", "g", "h"],
datasets: [
{data: chartData},
],
};
const canvasRef = useRef<HTMLCanvasElement>(null);
var myChart: Chart;
useEffect(() => {
const ctx = canvasRef.current?.getContext("2d");
if (ctx) {
var myChart = new Chart(ctx, {
type: "radar",
data: barChartData,
options: { responsive: true },
});
}
}, []);
useEffect(() => {
if (chartData != [0, 0, 0, 0, 0, 0, 0, 0]){
const barChartDataUpdated: Chart.ChartData = {
labels: ["a", "b", "c", "d", "e", "f", "g", "h"],
datasets: [ { data: chartData } ],
};
myChart.data = barChartDataUpdated;
myChart.update();
}
}, [chartData]);
return (
<div className="self-center w-1/2">
<div className="overflow-hidden">
<canvas ref={canvasRef}></canvas>
</div>
</div>
);
From what I understand, the second useEffect ends up in a situation where it is triggered before the Chart is actually instantiated.
I tried to modify the code to put the update in the same useEffect as the myChart creation, and it works, but everytime chartData is created, a new Chart is created on top of the previous one, which is quite buggy.
useEffect(() => {
const ctx = canvasRef.current?.getContext("2d");
if (ctx) {
var myChart = new Chart(ctx, {
type: "radar",
data: barChartData,
options: { responsive: true }
});
myChart.data.datasets = [ { data: chartData } ]
myChart.update();
}
}, [chartData]);
I have also tried to create the object outside of useEffect, which doesnt work at all.
What is the proper way to update myChart when chartData is updated?