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

230
Views
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
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!