getting cannot read properties of undefiend when fetching api in react

Viewed 54

I am working on an api and when I console.log(data.city) then it gives me result but if I add console.log(data.city.name) then it shows undefined. In console I'm getting the 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

2 Answers

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);
  }

Why default state defined as array? As i can see there is no array in response, so it's better define default state as null.

const [data,setData] = useState(null);

And then you can use ? instead of if statement

console.log(data?.city?.name);
Related