June 30, 2024

Fetching with JavaScript: A Simple Guide

In today’s world, web applications are becoming more interactive and dynamic, with real-time data fetching playing a crucial role. One common feature is displaying random quotes on a webpage. This blog post will walk you through a simple example of how to fetch and display random quotes using JavaScript.

Below is the complete code for fetching quotes from an API and displaying them on a webpage:

// show random number
const quoteTextEl = document.getElementById('quote_wrapper');
const authorName = document.getElementById('quote_author');
function newQuote() {
    const quote = apiQuotes[Math.floor(Math.random() * apiQuotes.length)];
    quoteTextEl.textContent = quote.text;
    authorName.textContent = quote.author;
}

let apiQuotes = [];

async function getQuotes() {
    const apiUrl = 'https://type.fit/api/quotes';
    try {
        const response = await fetch(apiUrl);
        apiQuotes = await response.json();
        newQuote();
    } catch (error) {
        // catch error here
    }
}
// on load
getQuotes();

Breaking Down the Code

1. HTML Elements:

const quoteTextEl = document.getElementById('quote_wrapper');
const authorName = document.getElementById('quote_author');

These lines get the HTML elements where the quote and the author’s name will be displayed. Ensure your HTML has elements with the IDs quote_wrapper and quote_author.

2. Function to Display a New Quote:

function newQuote() {
    const quote = apiQuotes[Math.floor(Math.random() * apiQuotes.length)];
    quoteTextEl.textContent = quote.text;
    authorName.textContent = quote.author;
}

This function selects a random quote from the apiQuotes array and updates the HTML elements with the quote text and author. It also logs the quote to the console.

3. Fetching Quotes from the API:

async function getQuotes() {
    const apiUrl = 'https://type.fit/api/quotes';
    try {
        const response = await fetch(apiUrl);
        apiQuotes = await response.json();
        newQuote();
    } catch (error) {
        console.error('Failed to fetch quotes', error);
    }
}

The getQuotes function fetches data from the API. It uses the fetch function to make a request to the API, then parses the JSON response and stores it in the apiQuotes array. If the request is successful, it calls newQuote to display a random quote. If there’s an error, it logs an error message to the console.

4. Loading Quotes on Page Load:

getQuotes();

Finally, the getQuotes function is called to fetch and display quotes as soon as the page loads.

How It Works

When the page loads, the getQuotes function is invoked, which makes a network request to the quote API. Once the data is fetched and stored in the apiQuotes array, the newQuote function is called to display a random quote on the page. The quote and author are displayed in the respective HTML elements and logged to the console.

Error Handling

The try...catch block in the getQuotes function ensures that any errors during the fetching process are caught and logged, preventing the application from crashing and providing useful feedback for debugging.

Conclusion

This example demonstrates how to fetch data from an API and display it dynamically on a webpage using JavaScript. By understanding and implementing this code, you can create interactive and dynamic web applications that provide real-time data to users. Happy coding!