Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
TypeError: Cannot destructure property when fetching data from an API. Can anyone explain this?

It is my first time working with an API and I'm having a little trouble here. I spent several hours today trying to figure this out, but I don't understand what I'm doing wrong. Would somebody be so kind to explain what's wrong with my code?

I'm trying to get data from the OpenWeather API. It usually works the first time It runs but then I'll just get this error in the console: Uncaught (in promise) TypeError: Cannot destructure property 'temp' of 'data.main' as it is undefined. As the method is called every 100 ms it just keeps flooding the console with this error. What's the matter here?

    /*Geolocation*/

let latUser = []
let lonUser = []


const errorCallback = (error) => {console.error(error)}
const successCallback = (position) => {
    latUser.push(position.coords.latitude)
    lonUser.push(position.coords.longitude)}

navigator.geolocation.getCurrentPosition(successCallback, errorCallback) 

/*Weather*/

const weatherText = document.querySelector(".wtext")
const weatherCelsius = document.querySelector(".wcelsius")
const weatherHumidity = document.querySelector(".whumid")
const weatherIcon = document.querySelector(".weather-icon")

let weather = {
    "apiKey": "*****",
    fetchWeather: function () {
        fetch("https://api.openweathermap.org/data/2.5/weather?lat=" + latUser[0] + "&lon=" + lonUser[0] +
         "&units=metric&appid=" + this.apiKey
        ).then((response) => response.json())
        .then((data) => this.displayWeather(data))
    },
    displayWeather: function(data){
        const { temp, humidity } = data.main
        const { description, icon } = data.weather[0]
        
        
        weatherText.innerText = description
        weatherCelsius.innerText = temp + "°C"
        weatherHumidity.innerText = "Humidity: " + humidity + "%"
        weatherIcon.innerHTML = '<img src="icons/' + icon + '.png">'

    }
}

setInterval(() => {weather.fetchWeather()
    
}, 100);
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda