Reza Savadkouhi

JavaScript – Dealing with REST API using .then()
Introduction

In this exercise, we will use JavaScript to fetch data from a REST API and manipulate the data. The API we will use is jsonplaceholder.typicode.com, which provides a collection of mock JSON data for web development.

Our task is to read all the posts from the API and change the title of even-id posts to uppercase. We will use a button to trigger the data fetch and processing.

Prerequisites
  • Basic knowledge of JavaScript
  • Familiarity with REST API
  • Knowledge of JSON structure
Understanding jsonplaceholder.typicode.com

jsonplaceholder.typicode.com is a popular service for providing mock data for web development. It offers a variety of endpoints that return JSON data representing different types of data structures, such as posts, users, and comments.

The posts endpoint provides a collection of mock posts, each with an ID, title, body, author, and other relevant properties. We will be using this endpoint to fetch data for our exercise.

Code Breakdown

Let’s break down the code step by step:

HTML
<p>Click to get posts from the source. Check console for the result.</p>
<!-- Using Event Listener -->
<button id="getpostButton">Get Posts</button>

This code defines a paragraph element that prompts the user to click a button to fetch posts from the API. The button element has an ID of getpostButton.

JavaScript
document.addEventListener("DOMContentLoaded", () => {
  const getpostButton = document.querySelector("#getpostButton");
  getpostButton.addEventListener("click", () => {
    // Send GET request to https://jsonplaceholder.typicode.com/posts
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then(response => response.json())
      .then(data => {
        // Iterate over the posts
        data.forEach(post => {
          // Check if id is even
          if (post.id % 2 === 0) {
            // Convert title to uppercase
            post.title = post.title.toUpperCase();
          }
        });
        // Log the updated data to the console
        console.log(data);
        // Also print the array as a table
        //console.table(data);
      })
      .catch(error => {
        console.error("Error:", error);
      });
  });
});

This code will fetch all the posts from the https://jsonplaceholder.typicode.com/posts endpoint and process the data. The document.addEventListener("DOMContentLoaded", () => {...}) part ensures that the JavaScript code is executed only after the DOM (Document Object Model) has been loaded.

The getpostButton.addEventListener("click", () => {...}) part attaches an event listener to the button with the ID getpostButton. The event listener will be triggered whenever the button is clicked.

Inside the event listener, the code fetches the data using the fetch() method. The then() method is used to handle the successful response, which is then passed to the response.json() method to parse the JSON data.

The data.forEach(post => {...}) loop iterates over the parsed posts array and checks if the post.id is even. If it is, the post.title is converted to uppercase using the toUpperCase() method.

Finally, the updated data is logged to the console using the console.log(data) statement.

Understanding .then()

The .then() method is a callback function that is used to handle the successful resolution of a promise. A promise is a JavaScript object that represents the eventual completion or failure of an asynchronous operation.

In our code, we use the .then() method to process the response data after the fetch() method has successfully retrieved the data from the API. The response.json() method is called on the successful response, and the parsed JSON data is passed to the .then() callback function.

The .then() callback function allows us to perform further processing on the data after it has been successfully retrieved. In our case, we iterate through the posts array and convert the title of even-id posts to uppercase.

The .then() method chains the asynchronous operations together, ensuring that each operation is executed only after the previous one has completed successfully. This prevents any errors from propagating through the chain and ensures that the data is processed in a controlled manner.

Conclusion

This exercise demonstrates the basic concepts of fetching data from a REST API and manipulating the data using JavaScript. By understanding the code and the role of .then(), you can build more complex applications that interact with APIs.

Leave a Comment

Your email address will not be published. Required fields are marked *