-1

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>)
A.v.
  • 49
  • 6
  • 1
    It will always be a promise. You should design the view such that it can deal with the fact that initially there will be no value. – Kevin B Oct 15 '20 at 19:44
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – zero298 Oct 15 '20 at 19:45

2 Answers2

0

All you can really do is to read the value from your component's state, and set the state when the promise resolves:

const [theValue, setTheValue] = useState(0); // or some other initial value, you choose what's best for your component

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;
}

useEffect(async () => {
    const array = await createArray();
    setTheValue(array[0]);
}, []);

return(
   <div>{theValue} </div>
)

You may want to alter your component to show some sort of loading indicator while waiting for the Promise to resolve.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34
0

You will need to create some state that you can update when the promises return:

// your state
const [data, setData] = useState(false);

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 = () => {
  Promise.all(
    idArray.map(id => getNumber (id))
  ).then( 
    // use setData to set whatever you want displayed
  );
}

// you render your data (or nothing if there is none)
return(<div>{data} </div>)
veddermatic
  • 1,082
  • 7
  • 15