w3resource

Fetch API and Error Handling in JavaScript

JavaScript Event Handling: Exercise-18 with Solution

Fetch API with Error Handling

Write a JavaScript program that fetches data from an API, handles network errors, and displays the results on a webpage

Solution 1: Using fetch data from an API

JavaScript Code:

// Function to fetch data from an API and display it
async function fetchData() {
  const apiUrl = 'https://jsonplaceholder.typicode.com/posts'; // API endpoint
  const resultContainer = document.getElementById('result'); // Div to display results

  try {
    const response = await fetch(apiUrl); // Fetch data from the API

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`); // Handle non-200 responses
    }

    const data = await response.json(); // Parse the response as JSON
    displayResults(data); // Call function to display the results
  } catch (error) {
    console.error('Fetch failed:', error); // Log errors to the console
    resultContainer.textContent = 'Error fetching data. Please try again later.'; // Show error message
  }
}

// Function to display fetched data
function displayResults(data) {
  const resultContainer = document.getElementById('result'); // Div to display results
  resultContainer.innerHTML = ''; // Clear previous content

  data.slice(0, 5).forEach((item) => {
    const p = document.createElement('p'); // Create a paragraph for each result
    p.textContent = `Post ${item.id}: ${item.title}`; // Add the title of each post
    resultContainer.appendChild(p); // Append the paragraph to the container
  });
}

// Add a button to trigger data fetch
const fetchButton = document.createElement('button');
fetchButton.textContent = 'Fetch Data'; // Button text
fetchButton.onclick = fetchData; // Set click event to fetch data
document.body.appendChild(fetchButton); // Add button to the DOM

// Add a container to display results
const resultContainer = document.createElement('div');
resultContainer.id = 'result'; // Set ID for styling or reference
document.body.appendChild(resultContainer); // Add container to the DOM

Output:

Fetch Data
Post 1: sunt aut facere repellat provident occaecati excepturi optio reprehenderit

Post 2: qui est esse

Post 3: ea molestias quasi exercitationem repellat qui ipsa sit aut

Post 4: eum et est occaecati

Post 5: nesciunt quas odio

Explanation:

    1. Fetching Data:

    • Uses the fetch API inside a try-catch block for better error handling.

    2. Error Handling:

    • Checks if the response is not OK and throws an error with the HTTP status.
    • Catches both network errors and non-200 responses.

    3. Display Results:

    • Dynamically displays the first 5 posts in a styled div.

    4. User Interaction:

    • Adds a button to trigger the fetch operation, ensuring flexibility.

Solution 2: Using Fetch with Promises

JavaScript Code:

// Function to fetch data from an API and display it
function fetchData() {
  const apiUrl = 'https://jsonplaceholder.typicode.com/posts'; // API endpoint
  const resultContainer = document.getElementById('result'); // Div to display results

  fetch(apiUrl)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`); // Handle non-200 responses
      }
      return response.json(); // Parse the response as JSON
    })
    .then((data) => {
      displayResults(data); // Call function to display the results
    })
    .catch((error) => {
      console.error('Fetch failed:', error); // Log errors to the console
      resultContainer.textContent = 'Error fetching data. Please try again later.'; // Show error message
    });
}

// Function to display fetched data
function displayResults(data) {
  const resultContainer = document.getElementById('result'); // Div to display results
  resultContainer.innerHTML = ''; // Clear previous content

  data.slice(0, 5).forEach((item) => {
    const p = document.createElement('p'); // Create a paragraph for each result
    p.textContent = `Post ${item.id}: ${item.title}`; // Add the title of each post
    resultContainer.appendChild(p); // Append the paragraph to the container
  });
}

// Add a button to trigger data fetch
const fetchButton = document.createElement('button');
fetchButton.textContent = 'Fetch Data'; // Button text
fetchButton.onclick = fetchData; // Set click event to fetch data
document.body.appendChild(fetchButton); // Add button to the DOM

// Add a container to display results
const resultContainer = document.createElement('div');
resultContainer.id = 'result'; // Set ID for styling or reference
document.body.appendChild(resultContainer); // Add container to the DOM

Output:

Fetch Data
Post 1: sunt aut facere repellat provident occaecati excepturi optio reprehenderit

Post 2: qui est esse

Post 3: ea molestias quasi exercitationem repellat qui ipsa sit aut

Post 4: eum et est occaecati

Post 5: nesciunt quas odio

Explanation:

    1. Fetching Data:

    • Uses the fetch API with Promises (then and catch) for handling asynchronous behavior.

    2. Error Handling:

    • Throws an error for non-200 HTTP responses and catches it in the catch block.

    3. Display Results:

    • Dynamically displays the first 5 posts in a styled div.

    4. User Interaction:

    • Adds a button to trigger the fetch operation, ensuring the user initiates the request.

Live Demo:

See the Pen javascript-event-handling-exercise-18 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Event Handling Exercises Previous: Build a Shopping Cart using JavaScript and SessionStorage.
Event Handling Exercises Next: Geolocation API in JavaScript for user Location Access.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.