JSON, API and APPs

I ended up creating a small project here → https://codepen.io/codeispoetry/pen/XWeWLrr?editors=1010 by using a free API.

How can I transition it to vanilla JS? Would it require advanced concepts such as fetch API or could it be done with some simpler Vanilla JS?

Well this is using fetch, which seems to be a sensible approach.

// helper for convenience
const getElem = (selector, root = document) => root.querySelector(selector)

fetch('https://freegeoip.app/json/')
    .then(response => response.json())
    .then(
        // destructuring to get data properties
        ({country_name, country_code, city, ip}) => {
            
            const countryClassName = `flag-icon-${country_code.toLowerCase()}`

            getElem('#country').textContent = country_name
            getElem('#city').textContent = city
            getElem('#ip-address').textContent = ip

            // with classList.add multiple classnames need to be comma separated
            getElem('#flag').classList.add('flag-icon', countryClassName)
        }
    )
    .catch((error) => {
        console.error('Error:', error);
    })

BTW, Initially I couldn’t get this to work. It turned out the chrome Ublock extention was preventing a fetch from freegeoip.app

1 Like