Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make API calls for each element in array

I'm using Next.js / React.js. I'm using this API to get a specific country.

There's an array on this response called borders, for example.

borders: [
   "CAN",
   "MEX",
],

There's an end point to get the data based on a border, for example.

https://restcountries.eu/rest/v2/alpha/can

How would I get the data both borders, i.e. each element in the borders array? It's two API calls that I've tried to make in a loop, but I get undefined.

export async function getServerSideProps(context) {
  const { name } = context.params;
  const res = await fetch(`https://restcountries.eu/rest/v2/name/${name}?fullText=true`)
  const countryRes = await res.json();

  const country = countryRes[0];

  // Get the borders
  const borders = country.borders;

  // I'm making an API call to each element in array
  const borderCountr = borders.forEach(border => {
    fetch(`https://restcountries.eu/rest/v2/alpha/${border}`);
  });

  console.log(borderCountr); // undefinded
  if (!country) {
    return {
      notFound: true,
    }
  }

  return {
    props: { country }
  }
}

1 Answers

A good approach would be using Promise.all, to be sure that each fetch is correctly executed. Also, you need to make those calls async. something like:

const borderCountr = await Promise.all(
  borders.map(async (border) => {
    const response = await fetch(`https://restcountries.eu/rest/v2/alpha/${border}`);
    return await response.json();
  })
);
    
console.log(borderCountr[0], borderCountr[1]);
like image 150
AdriSolid Avatar answered Oct 31 '25 16:10

AdriSolid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!