Chartjs-Chart.js data does not show up on initial page load

1👍

Your problem is that your second useEffect hook is not recalled when nethkinData gets updated, you should compute nethkinData into a useMemo and then add it as a dependency array of your second useEffect.

const nethkinData = useMemo(() => {
  return {
    labels: backendData.map((time) => time.time),
    datasets: [
      {
        data: backendData.map((total) => 30 - total.total),
        label: "Empty parking spaces",
        fill: true,
        backgroundColor: "rgba(211,211,211,0.5)",
        borderColor: "rgb(211,211,211)",
      },
    ],
  };
}, [backendData]);

// ...

useEffect(() => {
  var ctx = document.getElementById("nethkinChart").getContext("2d");
  let nethkinChartStatus = Chart.getChart("nethkinChart");
  if (nethkinChartStatus != undefined) {
    nethkinChartStatus.destroy();
  }
  var nethkinChart = new Chart(ctx, {
    type: "line",
    data: nethkinData,
    options: nethkinOptions,
  });
}, [nethkinData]);

Leave a comment