4👍
Turns out it was the very simple problem that the app was trying to render the component before the data had arrived, so I had to use some more state to check for data arrival before returning:
export default function App() {
const [chartData, setChartData] = useState({});
const [haveData, setHaveData] = useState(false); //here
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch('/api');
const data = await res.json();
setChartData(data);
setHaveData(true); // here, and importantly after the above setChartData call
} catch(error) {
setHaveData(false);
setError(error);
}
}
fetchData();
}, []);
if (!haveData) { // here
return <div>Loading...</div>
} else {
return (
<div className="App">
<ErrorBoundary>
<Chart chartData={chartData} />
</ErrorBoundary>
</div>
);
}
}
Easy fix, though not trivial to track down, and I’m a little bummed that the libraries don’t handle the lack of data a little more gracefully.
- [Chartjs]-Series Details Not Showing in Angular Chart with Charts.js
- [Chartjs]-Filter a legend Item with Chartjs.org V2.7
Source:stackexchange.com