Geek Logbook

Tech sea log book

50projectsIn50days – Day 10: Dads Joke

A simple container shows us a Dad Joke. If you click the button, another card will appear. The HTML and CSS are simple and don’t have anything special to point out. What is different is in JavaScript because the script loads the Jokes which come from icanhazdadjoke.

Firs of all you need to send in the header the key ‘Accept’ with the value ‘application/json’ in order to receive the following response:

{
    "id": "IRZDtWSnWDd",
    "joke": "Why do pumpkins sit on people’s porches?\r\n\r\nThey have no hands to knock on the door.",
    "status": 200
}

In curl it looks like as something as:

curl --location 'https://icanhazdadjoke.com' \
--header 'Accept: application/json'

To work with this response in JavaScript we are going to use the fetch() method. If you want to use this method you will notice that you don’t have the data payload. Instead of that you’ll receive a promise. As the official documentation says:

The global fetch() method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available.

Returns -> A Promise that resolves to a Response object.

Mozila Documentation

The call to the API will look like something as:

    const config = {
        headers: {
            'Accept': 'application/json'
        }
    }

    const res = await fetch('https://icanhazdadjoke.com', config)

If you want to create a function which retrieves the data instead of promise you will need to use async/await.

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or at the top level of a module.

Mozzila Documentation

Therefore the function generateJoke() will be like the following below:

async function generateJoke() {
    const config = {
        headers: {
            'Accept': 'application/json'
        }
    }

    const res = await fetch('https://icanhazdadjoke.com', config)

    const data = await res.json()

    jokeEl.innerHTML = data. Joke
}

You can see the code in this GitHub Repository: 10.dads_joke and the demo of the project is here: Dads Joke

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*