Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading