I am really struggling to wrap my head around async api calls. I am trying to render some data from an api call in my react application. The structure is as follow: Essentially, my thought process is that I am using fetchYearlyData to return the data from an api call. Then that data is processed in percentileRank to return a value. The main function calls the fetchYearlyData and percentileRank function in order.
const fetchYearlyData = async (year, stat) => {
let response = await fetch(
`http://localhost:5000/api/yearly_data/${year}/${stat}`
);
return response.json();
};
const percentileRank = (data, stat, percentile) => {
data = data.map((item) => {
return parseFloat(item[stat]);
});
let sortedArray = data.sort((a, b) => a - b);
let rank = Math.floor((percentile / 100) * (sortedArray.length + 1));
return sortedArray[rank];
};
export const main = async (year, stat, rank) => {
// Make API Call
let data = await fetchYearlyData(year, stat);
// Return data array
return percentileRank(data, stat, rank);
};
So far there are no issues.
But when I try and bring this into my react component for graphing purposes, I seem to be getting the data back as a promise instead of actual values, which prevents the graph from forming.
const data = {
labels,
datasets: [
{
label: "25th percentile",
data: labels.map(async (year) => {
let result = await main(year, props.statSelection, 25);
return result;
}),
},
],
};
return (
<div id="chart">
<Line options={options} data={data} />
</div>
);
I am completely lost, in that I am using async and await and still keep seeing promises, which is very frustrating. I would forever be in your debt if someone could explain this to me :)
Thanks!