Home > Enterprise >  My code is saying 'Cannot read properties of undefined'
My code is saying 'Cannot read properties of undefined'

Time:09-03

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

CodePudding user response:

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'));
  • Related