fetch data from an endpoint and display single record in a modal in JavaScript

Hello Codefussionist!

Today we are going to be creating an exciting tutorial on JavaScript. We are going to fetch data from an endpoint and display the records in a card, and at the same time we want to be able to preview each record when we click on the “view more” button.

Before we delve straight into coding let us some reasons why records should be viewed individually.

Benefits of Previewing Single Record From an Endpoint

  1. Enhanced User Experience: Previewing a single record can also benefit end-users by providing them with a more streamlined and responsive experience. Instead of waiting for large datasets to load, users can quickly preview individual records, leading to faster page load times and improved usability.
  2. Reduced Bandwidth Usage: Previewing a single record reduces the amount of data transferred between the client and server, resulting in lower bandwidth usage. This is particularly advantageous for mobile applications or low-bandwidth environments where minimizing data transfer is important for performance and cost efficiency.
  3. Fine-tuning Queries: When working with endpoints that support filtering or querying parameters, previewing a single record allows developers to fine-tune their query parameters and test their effectiveness in retrieving the desired results. This iterative approach helps optimize query performance and accuracy.

All right. Let’s start coding now. We want want to be able to display the names, images, emails and contributions of users in a Bootstrap card. We will be using two endpoints from reqres:

  1. https://reqres.in/api/users?page=2 — to list all users
  2. https://reqres.in/api/users?id=${id} — to view a single user

Now take the first link and paste in your browser. You should get the following response below:

Next, we will consume the endpoint using fetch:

Here’s the response:

JavaScript Fetch API

Next, we need to loop through this response and display the results in a card:

We’ll add our HTML:

Here’s what you should get so far:

Next, we need to add our modal class. But before we do that we need to create a function and pass the user id and we will be making use of the second endpoint. We will modify our button as follows:

We will create our readMore() function:

Next, we need to add our modal as follows:

Here’s the full code:

Here are the results:

When we click on the read more button, it brings out details of that particular user in a modal.

codefussion tutorial

This is it guys! This is how to fetch data from an endpoint and show single user in a modal in JavaScript. Let me know what you think in the comments.

By admin

One thought on “Fetch Data From an Endpoint and Show Single User in a Modal in JavaScript”

Leave a Reply

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