[Chartjs]-Creating Chart.js using API data in react

1👍

Your html file in the part where you are going to draw the chart should look something like this:

<div class="canvasContainer" style="margin-top:20px; margin-bottom:20px;">
  <canvas id="doughnut-chart"></canvas>
</div>

The first think that come to my mind is if there is any data at all coming from your getData function, if data is flowing in then my next guess is that setData is not updating it in time by the time you decide to use the variable data in your code.
I found this on a google search

State updates are asynchronous. This was true in class-based components. It’s true with functions/Hooks

And

Even though they are asynchronous, the useState and setState functions do not return promises. Therefore we cannot attach a then handler to it or use async/await to get the updated state values

So, there it lays your problem. You need to redefine the part where you fetch the data and the part where you set your chart up, since the await part is not functioning like you think it is for hook functions. Something like this.

useEffect(() => {
  getData() // it handles the setting up the data variable part
}, []); // If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument.

useEffect(() => {
  refreshToken();
  getChart(); // it only sets the chart up, nothing else
}, [data]); // our component re-renders with every change on the var data

You can have as many useEffect blocks as you like and you can get rid off the part getContext("2d") from your ctx.

Leave a comment