Why some attributes inside this weather Obj are accessable(first layer), but second layer cannot be accessed? See below
CodePudding user response:
There is something wrong with your url, also on the first render weather.main.temp
is undefined, because the api request is async code. The code below is working here:
const Weather=(props)=>{
const{capital, api_key} = props;
const [weather, setWeather] = useState('');
useEffect(() => {
axios
.get(`https://api.openweathermap.org/data/2.5/weather?q=${capital}&appid=${api_key}`)
.then(response => {
setWeather(response.data)
})
}, [])
console.log('weather', weather)
return(
<div>
<div> temperature {weather.visibility} Celcius</div>
<img src='http://openweathermap.org/img/wn/[email protected]' alt="flag" width="120" height="100"></img>
<p>wind {weather?.main?.temp} m/s</p>
</div>
)
}