DEV Community

Cover image for Day 58: Consuming Open Weather API
Margaret W.N
Margaret W.N

Posted on • Edited on

Day 58: Consuming Open Weather API

I worked on updating weather data on my webpage. I'm consuming the data from open weather API. I was hoping I'd set up an autocomplete with Spott API but since It is not working yet, I'll use OpenWeather API to search cities.

The code:

const input = document.getElementById("input");
input.addEventListener('keyup', async (event) => {
    event.preventDefault();
    if (event.keyCode === 13) {
        const typedString = document.getElementById("input").value;

        await axios(`https://api.openweathermap.org/data/2.5/weather?q=${typedString}&APPID=72a730baaa2ebd7a0edabe3d09b870c2`, {
            "method": "GET"
        }).then(response => {
            let data = response.data
            console.log(data);

            const city = document.querySelector('.city');
            city.textContent = `${data.name},`

            const country = document.querySelector('.country');
            country.textContent = data.sys.country

            const weather = document.querySelector('.weather');
            weather.textContent = data.weather[0].description

            const temp = document.querySelector('.degrees')
            temp.textContent = `${Math.round(data.main.temp - 273.15)}°`;

            const humidity = document.querySelector('#humidityRate')
            humidity.textContent = `${data.main.humidity}%`

            const cloudRate = document.querySelector('#cloudRate');
            cloudRate.textContent = `${data.clouds.all}%`

        }).catch(err => {
            console.log(err);
        });
    }
})
Enter fullscreen mode Exit fullscreen mode

The code explained:
I am attaching an event listener to the input element: keyup which will fire when a key is released. Since I do not want the event to keep firing every other time. I have specified that I only want the event to fire when the user hits enter, keyCode 13. Next, I am making a get request to Open weather API then updating the data received to my page. I switched to Axios because I had a hard time working with JSON while using fetch. Axios on the other hand automatically transforms JSON which makes it easier for me to work with.

Here is the repo: Weather App Repository.

I am also updating the date and time with javascript:

let today = new Date()

const day = document.querySelector('#day');
day.textContent = `${today.getDate()}th`

const month = document.querySelector('#month');
month.textContent = today.toLocaleString('default', { month: 'long' })

const year = document.querySelector('#year');
year.textContent = today.getFullYear()
Enter fullscreen mode Exit fullscreen mode

That was all for the day.
Day 58

Top comments (0)