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();
}, []);
>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);
}
