4

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
  • Array.forEach doesn't return anything. You need const borderCountr = await Promise.all(borders.map => fetch(...).then(r => r.json())); Commented Mar 6, 2021 at 12:14

2 Answers 2

6

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]);
Sign up to request clarification or add additional context in comments.

Comments

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

This is not awaited (you do not await for ANY of the fetch results) that mens, the code executes here, and without waiting for the fetches to finish - executed the next lines. As forEach returns undefined, that is your variable content.

2 Comments

I'm getting the following error when I add await in front of fetch - Syntax error: 'await' is only allowed within async functions and at the top levels of modules
1st - fetch is not written in function that is async, so await cannot be written there. If you add async to the arrow function, then you would be able to write await

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.