Get Price of Dogecoin using API Day 2 Coding Challenge - SebCodesTheWeb
Tags: javascript, webdev
Published: 2021-12-24 09:54:11

# 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](https://scrimba.com/learn/frontend) 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](https://www.youtube.com/channel/UCikWIcChAOSwoc2qpbZ6iIA), so feel free to follow along my journey and learn with me!

Watch the follow-along youtube video: 

{% youtube iZ_zIoZel7w %}


## 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1640292666594/vdJYtt5ui.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:
````javascript
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: 

```javascript
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](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API), and  the [openweatherapi](https://openweathermap.org/api), to get the weather of the users specific location:

```javascript
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:

```javascript
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!
<iframe src="https://giphy.com/embed/beBy7w1gklos0" width="480" height="360" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="https://giphy.com/gifs/beBy7w1gklos0"></a></p>

Follow my  [Youtube-channel](https://www.youtube.com/channel/UCikWIcChAOSwoc2qpbZ6iIA)  and my  [blog](https://sebcodestheweb.hashnode.dev/) 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.