Using a for loop in JavaScript to fetch and display a specified number of results from an API

Recently, I delved into the world of Javascript and API arrays to grasp the concept of retrieving and manipulating various APIs.

The topic of Javascript loops and arrays has been discussed numerous times, both here on StackOverflow and on other platforms.

Despite my efforts, I have struggled to pinpoint exactly what I need, perhaps due to my limited knowledge and search terms.

My current venture involves creating a WebApp that fetches data from an API (specifically the random user API) and showcases this data on the screen.

Execution and Challenge

Thus far, my focus has been on retrieving specific data from the API (with some success) and displaying it on a web browser. I aim to display multiple users simultaneously, limiting it to 15 users at a time (refreshing the browser should display another 15 random users from the API).

While I understand I can request multiple users directly using the results parameter, I am striving to accomplish this task using loops to enhance my understanding of fetching and displaying multiple sets of information.

Execution Strategy

  • The HTML file: It's pretty basic, containing a main div with an unordered list element. I plan to remove certain elements from the HTML and create them dynamically in the JS file using the innerHTML method as I progress.

  • CSS file: Currently minimalistic, as I'm prioritizing the JS file for now.

  • The Javascript file: Also simple at this stage. It includes a constant variable with the API URL, fetches data in JSON format, and then populates specific information (like first name and photo) in their designated IDs using document.getElementById().

My research has provided me with a foundational understanding of retrieving and displaying API data. However, I've hit a roadblock in understanding how to utilize for-loops or map() to iterate through my existing JS code and display data multiple times for multiple users.

Challenge Faced

Prior to integrating the for-loop, the JS file successfully retrieved information for a single random user, which was expected. However, upon adding the for-loop, it ceased to display anything without any helpful error messages to guide me through the issue.

To ensure I grasped the basics, I tested a simple for-loop that printed results in the console:

for ( var i = 0; i < 15 ; i++) {
    console.log(i)
}

I've linked the code snippets to a JSbin URL. There, you can review the current status and the encountered issue.

Current HTML + JS files and output (JS Bin): I've commented out the for-loop to demonstrate its functionality up to a certain point.

const testapi = fetch("https://randomuser.me/api/?gender=male");


/*for ( var i = 0; i < testapi.length ; i++) {*/
testapi
.then(data => data.json())
.then(data => document.getElementById('test').innerHTML = "<h1>" + data.results[0].gender + "</h1>" + "<p>" + data.results[0].name.first + "</p>" + document.getElementById("myImg").setAttribute('src',data.results[0].picture.medium))

.catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

/*}*/
li {
  display:flex;
  flex-direction: column;
  align-items:center;
  box-shadow: 2px 4px 25px rgba(0, 0, 0, .1);
}
<!DOCTYPE html>
<html lang="eng">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <div>
      <ul>
        <li>
          <div id="test"></div>
          <img src="" id="myImg" />
        </li>
      </ul>
    </div>
    <script src="script.js"></script>
  </body>
</html>

Useful Websites Visited

Answer №1

Give it a shot - I recursively call the function in the resolve block if there are more URLs to fetch:

Check out example 2 for using template literals

let cnt = 0;
const maxNum = 3;

function getEm() {
  if (cnt >= maxNum) return; // stop

  fetch("https://randomuser.me/api/?gender=male")
    .then(data => data.json())
    .then(data => {
      document.getElementById('test').innerHTML += '<li>'+
      "<h1>" + data.results[0].gender + "</h1>" + 
      "<p>" + data.results[0].name.first + "</p>" + 
      '<img src="'+data.results[0].picture.medium+'"/>'+
      '</li>';

     // recursion happens here

      cnt++; 
      getEm()

    })
    .catch(function(err) {
      console.log('Fetch Error :-S', err);
    });
}
getEm()
li {
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 2px 4px 25px rgba(0, 0, 0, .1);
}
<!DOCTYPE html>
<html lang="eng">

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
  <div>
    <ul id="test">
    </ul>
  </div>
  <script src="script.js"></script>
</body>

</html>

Fetching multiple users at once using template literals:

let users = []
fetch("https://randomuser.me/api/?results=15")
  .then(data => data.json())
  .then(data => {
    for (user of data.results) {
      users.push(
        `<li>
          <h1>${user.gender}</h1>
          <p>${user.name.first}</p>
          <img src="${user.picture.medium}"/>
        </li>`);
    }
    document.getElementById('test').innerHTML= users.join("");
  })
li {
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 2px 4px 25px rgba(0, 0, 0, .1);
}
<div>
  <ul id="test"></ul>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The dropdown menu is extending outside the header in a right-to-left (RTL) direction

I have implemented the jQuery code below to prevent the dropdown from extending beyond the header area. It works perfectly in the normal LTR version. However, I need a solution for the RTL version. How can I achieve this? jQuery $('.primary-menu .dr ...

What are some techniques to create a dynamic background for a div that

I've been attempting to create responsive background images within a div element, but unfortunately, my current method is not producing the desired results. Below is an excerpt of my CSS code: .block-main{ background: url(images/ohdaihiep/bg1. ...

What is the best method to close a polygon infowindow when hovering over a map marker?

I am currently working on integrating Google Maps which includes a set of polygons representing state boundaries and markers representing cities within each polygon. I want to display information when hovering over a polygon/state. My question is: how can ...

Modify the layout of a JSON data structure

Here is an example of an array: let array = [ {1: { "date": "2014-04-23 00:00:00", "volumetrie": "22458" }}, {2: { "date": "2014-05-02 00:00:00", "volumetrie": "30585" }}, {3: { "date" ...

Issue with loading function in FullCalendar React integration

Currently experimenting with FullCalendar v5 for React and exploring the Resource Timeline view feature. Facing an issue with the "loading" function - the idea is to monitor the state of FullCalendar and, if it's in a loading state, display a Spinner ...

Display the item request form whenever a selection of an unidentified item is made using select2

I want to implement select2 for a company search feature. In case the desired company is not available in the existing dataset, I need to provide an option for users to request adding the company data. This is the HTML code: <head> <link href=& ...

Vue.js data does not exhibit reactivity

I am encountering an issue with a non-reactive data object nested inside another object in my Vue.js template. Here is the code snippet: <template> <div> <b-container class="bg-white text-center scrollBehavior" > ...

Identifying and Blocking Users from Accessing External Domains Outside of the Angular Application

I am working on an angular application and I need to implement a feature where I can detect when a user navigates outside of the app domain from a specific component. For instance, let's say the user is on the upload component processing important in ...

Generating .npy data with Numpy to use as input for a Convolutional Neural Network

I am a beginner in Python and working with a .npy file as input for my CNN model. Many tutorials I have found use Keras, but unfortunately I am not permitted to use it. Therefore, I need to know how to read just one array from my .npy file. The file contai ...

What is the best way to display cards next to each other on desktop and mobile devices while maximizing available space?

In the world of React components, there exists a card representation within a grid view that adapts based on available screen space; function EngineerCard(engineer: EngineerDetail) { return ( <div className='engineerCard'> <d ...

Hide modal once form has been successfully submitted

Is it best practice to pass handleClose into ForgotPasswordFormComponent in order to close the modal after form submission, or is there a better way to achieve this? <StyledModal open={openModal} onClose={handleClose} closeAfterTransition slots={{ bac ...

Issue: Catching errors in proxy function calls

I am currently using Vue 3 along with the latest Quasar Framework. To simplify my API calls, I created an Api class as a wrapper for Axios with various methods such as get, post, etc. Now, I need to intercept these method calls. In order to achieve this ...

Access the value of a variable passed from the view to the controller

Is there a way to retrieve a dynamically generated value from the view to the controller in AngularJS? <ng-option ng-repeat="w in details track by $index"> <div class="program-grid-row table-row" > <div> <a class= ...

The Mongoose connection status is consistently showing as 0

Utilizing nodejs and mongoose to establish a connection with my MongoDB Database. I am attempting to check the connection state, specifically if it is connected or not. I am using mongoose.connection.readyState to achieve this. The connection seems to be ...

Is there a way to position headline text behind another headline? Take a look at the image provided for reference

I need help creating headline text with a background image similar to the example below. I tried using relative positioning on the first heading, but I can't seem to get it to work correctly. If anyone can provide me with the code to achieve this ef ...

Responsive columns with maximum width in Bootstrap

Currently, I'm working on coding a portion of a single-page responsive Bootstrap layout that features two columns of text placed side by side. The request from the designer is for these columns to have a maximum width, but to be centered until they hi ...

Setting up an OnMouseOver event for each URL on a webpage

Is there a way to add an OnMouseOver event for all anchor tags on a page, without replacing any existing event handlers that are already in place? I'm looking for guidance on how to achieve this using JavaScript or JQuery. Any suggestions would be gr ...

Incorporate a button within the input field

Looking to customize my search form with the search button on the right side, similar to this: https://i.sstatic.net/lwmig.png Below is the code for my current form setup: <form action="search.php" method="post" class="index-search-form"> ...

Dealing with errors in Express.js within the service or controller layers

Currently, I am developing an Express.js application with a distinct controller layer and service layer. Below you can find the code snippet I have implemented so far: user.service.js exports.registerUser = async function (email, password) { const hash ...

Having trouble setting up email with Passport-local. Any new suggestions?

I have been working on implementing user log-in using passport-local and express. While I have successfully managed to achieve log-ins with usernames, I find them hard to remember and not ideal for user authentication. Therefore, I attempted to customize t ...