Is there a way to retrieve multiple results by utilizing fetch and randomuser.me?

I am currently working with the randomuser.me API and have set up the fetch request correctly. My goal is to retrieve 5 users separated by commas instead of just one.

As mentioned in randomuser.me's documentation, I simply need to append the fetch URI with ?results=5 (or any desired number) to receive multiple users.

Despite implementing this in the code snippet below, I am still only getting a single user back.

How can I modify my code to return a comma-separated list of 5 users?

window.onload = () => {
  randomUserGenerator();
};

const randomUserGenerator = () => {
  fetch("https://randomuser.me/api/?results=5")
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      showRandomUserData(data);
    });
};

showRandomUserData = (randomUser) => {
  document.getElementById("name").innerText = 
    `${randomUser.results[0].name.first} ${randomUser.results[0].name.last}`;
};
<h3><u>Users:</u> <span id="name"></span></h3>

Answer №1

Don't just stop at results[0] ... remember, you're only utilizing the information for one user

If you try something like this instead, it could be beneficial:

window.onload = () => {
  randomUserGenerator();
};

const randomUserGenerator = () => {
  fetch("https://randomuser.me/api/?results=5")
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      showRandomUserData(data);
    });
};

showRandomUserData = (randomUser) => {
  // merge details of all users
  const users = randomUser.results.map(({name: { first, last}}) => `${first} ${last}`).join(', ');
  // display them
  document.getElementById("name").innerText = users;
};
<h3><u>Users:</u> <span id="name"></span></h3>

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

Automatically increase the height of a text area as you type beyond the maximum width limit

Is there a way to dynamically expand the textarea width as I type beyond its maximum set width without displaying a horizontal scrollbar? Here is the HTML code in its rendered form: <textarea name="CatchPhrase" class="inp ...

Whenever I attempt to generate a forecast utilizing a tensorflow.js model, I encounter the following error message: "Uncaught TypeError: Cannot read property 'length' of undefined."

I'm currently working on a project to build a website that utilizes a deep learning model for real-time sentiment analysis. However, I've encountered an issue when using the model.predict() function. It throws an error message: Uncaught TypeErro ...

What is the process for extracting information from a middleware within a Next.js framework?

I have been working on developing an authentication system using JWT in Next.js. In order to achieve this, I created a middleware that can validate the JWT token and establish an authentication process as shown below: export default function middleware(req ...

Diminishing of the darkness

Imagine a tree adorned with beautiful alpha leaf textures. The intricate pattern of the falling shadow casts a deep darkness on the leaves "below", causing the entire model to appear dark. https://i.sstatic.net/N5ocS.png https://i.sstatic.net/EL5BZ.png ...

Having trouble importing Angular flex-layout into my feature module

I'm facing an issue with Angular flex-layout in one of my modules. It works perfectly fine when I import flex-layout in the app module, but only for the app component. However, when I import flex-layout in another module, it doesn't seem to work ...

Issue when sending PHP Papa Parse object through AJAX

I am currently working on extracting a CSV local file in PHP using AJAX and have found success with Papa Parse. However, I am facing difficulties passing the results with AJAX. Despite trying various methods such as JSON.stringify, passing only the first f ...

Using Hapi & Async for your API - How can you clear an array or execute a function immediately after sending a "reply" or at every new "get" request?

In the midst of developing a small API that retrieves data, performs tasks on it asynchronously, stores some of this data in an array using push, and then presents it to a client through Hapi's reply(). My goal is to clear out the array (e.g., using ...

Concealing an element from a separate module

In the angularjs single page application project that I'm working on, there are two modules: module-'A' and module-'B'. Each module has its own view templates. The view template of module-'B' contains a div with id="sit ...

The format of the date cannot be modified when using DesktopDatePicker as a React Component

I've been attempting to modify the appearance of the component, but the UI keeps showing the date in month-year format. <DesktopDatePicker inputVariant="outlined" label="Pick-up date" id="date ...

Troubleshooting problem with list rendering in a Nativescript-vue GridLayout

As a newcomer to nativescript, I am utilizing GridLayout in an attempt to optimize layout nesting for better performance. In my template, I have an image followed by a vertical list of four items next to it. However, only the first item on the list is visi ...

The issue of Next.js redux useSelector causing HTML inconsistency

Currently, I am utilizing Next.js for the development of a React application. In order to manage the state, I have integrated redux along with redux-toolkit. A peculiar error has surfaced in the console with the message: Warning: Did not expect server H ...

Merging data sets with Javascript: A comprehensive guide

As a newcomer to the world of javscript, I'm faced with what seems like a simple question. I'm working with two datasets that contain a common column and I'd like to merge them together. The structure of the datasets is as follows: const da ...

Having trouble with TypeScript error in React with Material-UI when trying to set up tabs?

I have developed my own custom accordion component hook, but I am encountering the following error export default const Tabs: OverridableComponent<TabsTypeMap<{}, ExtendButtonBase<ButtonBaseTypeMap<{}, "button">>>> Check ...

Obtaining the source code in CKEditor while in edit mode with Rails

As a Rails developer, I recently utilized CKEditor in one of my applications. After writing a sample HTML source code in the editor and submitting it, the code displayed properly on the front-end as a GUI. However, when attempting to edit the source code f ...

No elements can be located within the iframe as per Cypress's search

I've been attempting to access elements within an iframe using the guidance provided in this article here, but I'm facing an issue where Cypress is unable to locate anything within the iframe. Below is a snippet of my test code: describe('s ...

Why is only the peak of the wave visible? I am eager to showcase the full extent of its beauty

Having an issue with the appearance of a superposed wave using threejs. When displayed, the wave made from plane material only shows the upper half, but when turned upside down using mouse dragging, it appears correctly. // Turn the wave plane upside down ...

Range slider position not being updated after user interaction

I am working on a webpage with an embedded video and a range slider that serves as a progress bar. Using Javascript, I update the value of the range slider as the video plays, allowing users to navigate through the video content. However, I have encounter ...

Tips for choosing option values from the browser console in Angular

Is there a way to choose one of the list values directly from the browser console? I appreciate any assistance provided <select style="width: 100%" id="Select1" class="css-dropdowns ng-not-empty ng-dirty ng-valid ng-valid-required n ...

Having trouble with Next-Auth's signIn with Credentials feature in NextJS?

I have recently added the next-auth package to my new Next.js project. Despite following all the documentation for both Next.js and next-auth, I am still unable to resolve the issue. The problem I am encountering is as follows: I am trying to log in to my ...

Utilize CamelCase in jQuery for Better Code Readability

Upon examining the jQuery source code, I noticed an interesting use of camelcase: camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } // where: rmsPrefix = /^-ms-/, rdashAlpha = /-([\da- ...