Chart JS displays data properly only on the second refresh of the page #794
-
On the first load, only two dogs are displayed, only upon refreshing five dogs are shown (which then is the same as the five dogs in the db) Because of the issue we tried to implement Our code looks like this :)
We think the data does not arrive in sync and that is why there is a delay in displaying ... but we do not know how to solve this ... Help -- as always -- appreciated! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I have not done much work with Chartjs but i get the feeling we don't need a useEffect to manage this. If we only create the chartData object after we are sure we have the data (i.e. after the if(!data) check) then i think we are good to go. I put together a brief demo using a space api (i.e. fetch data with useswr and then pass it into the Doughnut component) and it seems to work ok. import React from "react";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Doughnut } from "react-chartjs-2";
import useSWR from "swr";
ChartJS.register(ArcElement, Tooltip, Legend);
const fetcher = (...args) => fetch(...args).then((res) => res.json());
export default function CustomChart() {
const { data, error, isLoading } = useSWR(
"https://api.nasa.gov/neo/rest/v1/neo/browse?api_key=DEMO_KEY",
fetcher
);
if (error) return <div>failed to load</div>;
if (isLoading) return <div>loading...</div>;
const spaceObjectNames = data.near_earth_objects.map(
(object) => object.name_limited
);
const spaceObjectDiameters = data.near_earth_objects.map(
(object) => object.estimated_diameter.kilometers.estimated_diameter_max
);
const chartData = {
labels: spaceObjectNames.slice(0, 5),
datasets: [
{
label: "Diameter in km",
data: spaceObjectDiameters.slice(0, 5),
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)",
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)",
],
borderWidth: 1,
},
],
};
return <Doughnut data={chartData} />;
} |
Beta Was this translation helpful? Give feedback.
So having just spoken with the group in person it turns out there were 2 issues.
splice
(which mutates) rather thanslice
(which creates a copy) that was also causing an issue.The demo above works (in that there is no need to use useEffect to sync up states).