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>
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
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); }); }
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
Open your
index.html
file in a web browser.Click the "Get a Joke" button.
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 ๐
Subscribe to my newsletter
Read articles from Gregor Schafroth directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Gregor Schafroth
Gregor Schafroth
Entrepreneur & Junior Programmer, currently learning how to build an OpenAI Assistant's API Chat-bot app with Python, Flask, Heroku, Celery, Redis, etc.