I’m trying to create a weather app. I wanted to update the weather data every 5 seconds by calling the async function every 5 seconds using setInterval()
. However, I get an error 400
const APIkey = 'c571c7fe39b869a406ab7e98d2f009c5';
const apiURL = 'https://api.openweathermap.org/data/2.5/weather?units=metric'
//Default city set to New York
const input = document.querySelector('input');
input.value = 'New York';
checkWeather();
let intervalID = setInterval(checkWeather, 5000)
const button = document.querySelector('button');
button.addEventListener('click', () => {
checkWeather();
clearInterval(intervalID);
intervalID = setInterval(checkWeather, 5000);
});
input.addEventListener('keyup', (event) => {
if (event.key === 'Enter') {
checkWeather();
clearInterval(intervalID);
intervalID = setInterval(checkWeather, 5000);
}
});
async function checkWeather(){
try {
const response = await fetch(apiURL + `&q=${input.value}&appid=${APIkey}`)
const data = await response.json();
const temp = document.querySelector('.temp');
temp.textContent = `${data.main.temp}°c`
const city = document.querySelector('.city');
city.textContent = data.name;
const windspeed = document.querySelector('.windspeed');
windspeed.textContent = `${data.wind.speed} km/h`
const humidity = document.querySelector('.humid');
humidity.textContent = `${data.main.humidity} %`
const clouds = document.querySelector('.cloud');
clouds.setAttribute('src',`images/${data.weather[0].main.toLowerCase()}.png`)
input.value = '';
console.log(data.main)
} catch (error) {
console.log('Error occured:', error.message);
const errorMsg = document.querySelector('.error-message');
errorMsg.style.display = 'block'
}
}
I tried to change the interval to a minute thinking that 5seconds is to quick but it still shows an error.