Search code examples
javascriptreactjsreact-hookses6-promise

Returning value instead of promise in useEffect in React


I have the following code,

let currencyValues = [];

const retrieveCurrencyPairs = async (pair) => {
    const r = await fetch(pair.url);
    const rParsed = await r.json();
    let newCurrencyValue = { currency: pair.countries, value: rParsed };
    return newCurrencyValue;
};

useEffect(() => {
    currencyValues = currencyPairs.map(retrieveCurrencyPairs);
    console.log(currencyValues);
}, []);

and the following expectations:

  • On page load, the useEffect triggers the function inside of the map()
  • For each value of the array, the retrieveCurrencyPairs() is triggered and awaits for the result, which is then returned
  • The currencyValues array is the filled with the 3 new objects

Unfortunately the function is returning promises, instead of the objects.

Any tip on how to return the objects instead?


Solution

  • async functions always return promises. You could do this instead:

    Promise.all(currencyPairs.map(retrieveCurrencyPairs))
      .then( results => ... )
    

    Promise.all has the additional benefit of running them all in parallel instead of sequentially.

    You might consider Promise.allSettled if you want to deal with individual failures/rejections without rejecting the whole list.