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

Pulling information from OpenWeatherMap API when state (country) changes

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

enter image description hereenter 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 :

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