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