I have some problem using async functions in functional component in React. I have a functional component that needs to render some number.
The function getNumber
: for each id, performs an API call to retrive a number (associated with the specific id).
The function createArray
creates an array of those numbers out of an array of ID's (idArray
).
The problem is that the return of the function(component) access value createArray() [0]
, and I get en error because the type is a promise (return don't wait for the async functions).
What is the best solution for this?
const getNumber = async (id: String) => {
const numberFromApi = await getNumberFromApi(id); //returns an object
return numberFromApi.num; //taking the num value out of the object
};
const createArray = async () => {
const arrayOfNumbers= await Promise.all(
idArray.map(id => getNumber (id))
);
return arrayOfNumbers;
}
return(
<div>{createArray()[0]} </div>)