Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Obtener información de la API de OpenWeatherMap cuando cambia el estado (país)

Actualmente, solo puedo extraer información cuando el nombre del país ya está cargado, agrego el código, lo guardo y luego se actualiza en localhost. Pero cuando escribo en otro país, aparece el error Uncaught TypeError: Cannot read properties of undefined (reading 'temp') . Por ejemplo, mi código {weather.main.temp} funciona pero solo cuando el estado = "francia" ya está configurado antes.

Mi subcomponente:

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

ingrese la descripción de la imagen aquí ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

weather se inicializa como un objeto vacío cuando se crea WeatherInfo . Por lo tanto, weather.main no está definido y obtiene el error cuando intenta obtener el atributo temp de undefined.

Puede resolver esto al tener algún encadenamiento condicional o algunos operadores ternarios dependiendo de lo que quiera que se muestre cuando weather es un objeto vacío.

 return ( <div> <h3>Weather in {country.capital}</h3> <p><b>Temperature</b>{weather.main?.temp}</p> </div> )
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!