-2

This is the code I used for the project and its working for country 1 but not for country 2. Country 2 is giving undefined error

 const getCountryData = function (country) {
  //country 1
  fetch(`https://restcountries.com/v3.1/name/${country}`)
    .then(response => response.json())
    .then(data => {
      renderCountry(data[0]);
      const neighbour = data[0].borders[0];
      console.log(data[0]);

      //if theres no neighbour return immedaitely
      //thats what the ! is for
      if (!neighbour) return;

      //country 2
      return fetch(`https://restcountries.com/v3.1/alpha/${neighbour}`);
    })
    .then(response => response.json())
    .then(data => renderCountry(data, 'neighbour'));
};
getCountryData('nigeria');

And this is the error output:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'png') at renderCountry (script.js:48:55) at script.js:158:19

Kleber Germano
  • 702
  • 3
  • 10
  • 25
Kukoyi Tomiwa
  • 15
  • 1
  • 8
  • Does this answer your question? [How to avoid 'cannot read property of undefined' errors?](https://stackoverflow.com/questions/14782232/how-to-avoid-cannot-read-property-of-undefined-errors) – Liam Sep 30 '22 at 11:44

1 Answers1

0

Note the difference between your two calls to renderCountry. The first calls the function with the first element of data, the second calls the function with the entire data array.

Try

.then(data => renderCountry(data[0], 'neighbour'));
James
  • 20,957
  • 5
  • 26
  • 41