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

getting cannot read properties of undefiend when fetching api in react

i am working on a api and when i console.log(data.city) then it give me result but if i add console.log(data.city.name) then it shows error undefined. in console i get result but after reload this error came.
also when first console is empty array and then second is data.

const [cityName, setCityName] = useState('delhi');
  const [data,setData] = useState([]);
  const getWeatherInfo = async () => {
    await fetch(
      `https://api.openweathermap.org/data/2.5/forecast?q=delhi&units=metric&appid=4beffc863037e89f0f181d893d1cf79b`)
      .then(res => res.json())
      .then((data)=> {
        setData(data)
      })
      .catch((err)=> {
        console.log('error' + err);
      })
  };

console.log(data.city.name);

  useEffect(() => {
    getWeatherInfo();
  }, []);

enter image description here

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

>Solution :

You are initialising the state as an empty array, thereby the element city doesn’t exist on the first render thus leading to an error.
You can fix this by logging only if the key city exists, as :

 if (data.city) {
    console.log(data.city.name);
  }
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