daily code 77 | js fetch practice

gregorschafroth

Gregor Schafroth

Posted on July 21, 2024

daily code 77 | js fetch practice

All JavaScript beginner courses I know ignore this topic, but in the age of APIs and AI this is really important: fetch.

Do you know now to use fetch?

Here is a very simple exercise to practice or brush up your fetch skills:

Exercise: Fetch and Display a Random Joke

Create a basic HTML structure:

  • Create an index.html file with the following content:
htmlCopy code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fetch Random Joke</title>
</head>
<body>
    <h1>Random Joke</h1>
    <button id="fetch-joke-button">Get a Joke</button>
    <p id="joke-display"></p>

    <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Create a JavaScript file to fetch the joke:

the API you can use is https://official-joke-api.appspot.com/random_joke

Can you do it?

You can find the solution from ChatGPT below:

Solution

  1. Create a script.js file with the following content:

    javascriptCopy code
    document.getElementById('fetch-joke-button').addEventListener('click', fetchJoke);
    
    function fetchJoke() {
        fetch('https://official-joke-api.appspot.com/random_joke')
            .then(response => response.json())
            .then(data => {
                document.getElementById('joke-display').innerText = `${data.setup} - ${data.punchline}`;
            })
            .catch(error => {
                console.error('Error fetching joke:', error);
            });
    }
    
    
  2. How it works:

    • When the "Get a Joke" button is clicked, the fetchJoke function is called.
    • This function uses the fetch API to send a GET request to the "Official Joke API" to get a random joke.
    • Once the response is received, it is converted to JSON format.
    • The joke's setup and punchline are then displayed in the paragraph element with the id joke-display.
    • If there is an error during the fetch operation, it is logged to the console.

Steps to Test

  1. Open your index.html file in a web browser.
  2. Click the "Get a Joke" button.
  3. Observe the random joke displayed on the page.

This exercise will help you understand the basics of making HTTP requests using the fetch API and handling the response data in JavaScript.

Hope you enjoyed!

Have a great day, and enjoy the random jokes 😉

💖 💪 🙅 🚩
gregorschafroth
Gregor Schafroth

Posted on July 21, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related