skip to Main Content

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
enter image description here

const APIkey = 'api_key_value';
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 too quick but it still shows an error.

2

Answers


  1. I could not replicate your 400 error, I think you have a request limit (more info here: https://openweathermap.org/faq).

    Take care with sharing your API KEY if you are using a paid version.

    I think you have to handle this kind of error when you need a third API for you. Verify if fetch was successful and then continue with some error message.

    Login or Signup to reply.
  2. As per the documentation 400 error occurrs because the required params are not passed to the API, and as per https://openweathermap.org/current you need to pass lat and lon to the API you are calling.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search