JavaScript Fetch API Examples

Explore 3 practical examples of JavaScript fetch API for real-world applications.
By Jamie

Introduction to the JavaScript Fetch API

The Fetch API is a modern interface that allows you to make network requests similar to XMLHttpRequest. It provides a more powerful and flexible feature set to interact with resources over the network. This API is widely used for fetching data from servers and handling responses in web applications. Below are three diverse, practical examples showcasing how to use the JavaScript fetch API in various scenarios.

Example 1: Fetching JSON Data from an API

Use Case

This example demonstrates how to fetch user data from a public API and display it on a webpage. It’s ideal for scenarios where you want to retrieve and display real-time information.

fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
    const userList = document.getElementById('user-list');
    data.forEach(user => {
      const li = document.createElement('li');
      li.textContent = `${user.name} - ${user.email}`;
      userList.appendChild(li);
    });
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

Notes

  • The jsonplaceholder.typicode.com is a free fake API for testing and prototyping.
  • Ensure to handle errors gracefully to improve user experience.

Example 2: Sending Data to a Server

Use Case

This example illustrates how to send data to a server using the POST method. It is useful in applications such as submitting form data or user-generated content.

const userData = {
  name: 'John Doe',
  email: 'john.doe@example.com'
};

fetch('https://jsonplaceholder.typicode.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(userData),
})
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json();
  })
  .then(data => {
    console.log('Success:', data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Notes

  • This example uses JSON.stringify to convert the JavaScript object to a JSON string for the request body.
  • Always ensure your server can handle the data format you are sending.

Example 3: Handling Multiple Requests with Promise.all

Use Case

This example showcases how to fetch data from multiple sources concurrently. This is particularly useful when your application needs to gather data from different APIs before rendering content.

const urls = [
  'https://jsonplaceholder.typicode.com/users',
  'https://jsonplaceholder.typicode.com/posts'
];

Promise.all(urls.map(url => fetch(url)))
  .then(responses => {
    return Promise.all(responses.map(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok ' + response.statusText);
      }
      return response.json();
    }));
  })
  .then(data => {
    const [users, posts] = data;
    console.log('Users:', users);
    console.log('Posts:', posts);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

Notes

  • Promise.all() is used to wait for all fetch requests to complete before proceeding.
  • This method is efficient for gathering data from multiple endpoints without blocking execution.