Get Price of Dogecoin using API Day 2 Coding Challenge - SebCodesTheWeb

Photo by Executium on Unsplash

Get Price of Dogecoin using API Day 2 Coding Challenge - SebCodesTheWeb

Christmas School Break is the Best Time to Code

Follow along my learning from CSS to React and Node in 20 days

Hello!

My name is Sebastian, and I'm a high-school student from Sweden. I have dabbled with some front-end development for the past few months. And since Christmas brake finally arrived, I've decided to start a challenge for myself! I'm going to code non-stop for the coming 20 days.

I'm following the front-end career path at Scrimba and I'm currently at module 7 (APIs)

By the end of the 20 days I'm hoping to have finished the front-end career path and have started with some backend Node.js development. I will be documenting my progress for the coming days, and filming myself on my Youtube-channel, so feel free to follow along my journey and learn with me!

Watch the follow-along youtube video:

Day 2 API:s App

Today I've built this web app. It displays the current time, weather and the price of cryptocurrencies! Screenshot (38).png

So how is this built? It is built using four API:s, one for the background image, one for the weather, one for the geographic location and finally one for the cryptocurrencies. It then uses some relatively easy HTML and CSS using Flexbox to show everything in a nice way.

The first API is from unsplash, and it selects a random image related to nature by using this code:

fetch("https://apis.scrimba.com/unsplash/photos/random?orientation=landscape&query=nature")
    .then(res => res.json())
    .then(data => {
        document.body.style.backgroundImage = `url(${data.urls.regular})`
        document.getElementById("author").textContent = `By: ${data.user.name}`
    })
    .catch(err => {
        // Use a default background image/author
        document.body.style.backgroundImage = `url(https://images.unsplash.com/photo-1560008511-11c63416e52d?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyMTEwMjl8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MjI4NDIxMTc&ixlib=rb-1.2.1&q=80&w=1080
)`
        document.getElementById("author").textContent = `By: Dodi Achmad`
    })

It then changes the background image of the body element to the URL of that image, it also accesses the author/photographer of that image. Finally it set's a default value for the image and author in case something was to go wrong in the fetch

Get Dogecoin Market Value

The second API uses coingecko.com, to get the current value, the highest value in the past 24h and the lowest value in the past 24h for a particular crypto coin of your liking:

fetch("https://api.coingecko.com/api/v3/coins/dogecoin") // Dogecoin Data
    .then(res => {
        if (!res.ok) {
            throw Error("Something went wrong")
        }
        return res.json() //Converting to JavaScript
    })
    .then(data => {
        document.getElementById("crypto-top").innerHTML = `
            <img src=${data.image.small} />
            <span>${data.name}</span> // Seting up DOM Image and Title
        `
        document.getElementById("crypto").innerHTML += `
            <p>🎯: $${data.market_data.current_price.usd}</p> //Market Price
            <p>πŸ‘†: $${data.market_data.high_24h.usd}</p>
            <p>πŸ‘‡: $${data.market_data.low_24h.usd}</p>
        `
    })
    .catch(err => console.error(err))

It uses (!res.ok) to check if any errors were thrown, for example a 404 or 505. If successful, it then gets the name, image, and market value of the coin of choice

Get Weather Data

The app also pairs together Geolocation, and the openweatherapi, to get the weather of the users specific location:

navigator.geolocation.getCurrentPosition(position => {
    fetch(`https://apis.scrimba.com/openweathermap/data/2.5/weather?lat=${position.coords.latitude}&lon=${position.coords.longitude}&units=imperial`)
        .then(res => {
            if (!res.ok) {
                throw Error("Weather data not available")
            }
            return res.json()
        })
        .then(data => {
            const iconUrl = `http://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`
            document.getElementById("weather").innerHTML = `
                <img src=${iconUrl} />
                <p class="weather-temp">${Math.round(data.main.temp)}ΒΊ</p>
                <p class="weather-city">${data.name}</p>
            `
        })
        .catch(err => console.error(err))
});

It accesses the geolocation API by using navigator.geolocation, it then accesses a position object containing keys accessing the longitude and latitude of the user. It then uses this coordinates as a query parameter to get the specific weather for that location.

Finally, the program also uses setInterval, to update the time with a live clock:

function getCurrentTime() {
    const date = new Date()
    document.getElementById("time").textContent = date.toLocaleTimeString("en-us", {timeStyle: "short"})
}

setInterval(getCurrentTime, 1000)

It calls the function getCurrentTime() every second, creating a Date-javascript object, and then updating the DOM with that info.

That was all the Javascript for this web app!

Follow my Youtube-channel and my blog so you can stay updated on the next challenge tomorrow, and continue to learn to code with me. Also it would make my day if you would smash that emoji to the top-right :)

Peace.

Β