Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>
)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda