Currently, I am only able to pull information when the name of the country is already loaded, I add the code, save it, then it’s updated on localhost. But when I type in another country I get the error of Uncaught TypeError: Cannot read properties of undefined (reading 'temp'). For example, my code {weather.main.temp} works but only when the state = "france" is already set before.
My sub component:
const WeatherInfo = ({ country }) => {
const [weather, setWeather] = useState({});
useEffect(() => {
axios
.get(`https://api.openweathermap.org/data/2.5/weather?q=${country.capital}&appid=${api_key}&units=imperial`)
.then(response => {
console.log(response.data)
setWeather(response.data)
})
}, [country])
return (
<div>
<h3>Weather in {country.capital}</h3>
<p><b>Temperature</b>{weather.main.temp}</p>
</div>
)
}
>Solution :
weather is initialized as an empty object when WeatherInfo is created. Therefore weather.main is undefined and you get the error when you try to get the attribute temp from undefined.
You can resolve this by having some conditional chaining or some ternary operators depending on what you want displayed when weather is an empty object.
return (
<div>
<h3>Weather in {country.capital}</h3>
<p><b>Temperature</b>{weather.main?.temp}</p>
</div>
)

