Issue with data retrieval (Uncaught (in promise) TypeError: Unable to access properties of undefined (reading 'map'))

Greetings! Upon executing this code, I encountered an error related to the map() method. Despite its apparent simplicity, the issue persists.

var div_usuarios = document.querySelector('#usuarios');
var usuarios = [];

fetch('https://jsonplaceholder.typicode.com/users')
    .then(data => data.json())
    .then(users=> {
        usuarios = users.data;
        console.log(usuarios);

        usuarios.map((user, i)=>{
            let nombre = document.createElement('h2');
            nombre.innerHTML = i + user.first_name + " " + user.last_name;
            div_usuarios.appendChild(nombre);

        })

    });

Is there a solution to rectify this issue?

Interestingly, the code mirrors that of an online course I am currently undertaking, yet it fails to function correctly for me!

Answer №1

Perhaps the data you are attempting to access has undergone changes over time, resulting in your code not performing as anticipated. Refer to the provided functional example below for guidance.

let userDiv = document.querySelector('#users');
let usersArray = [];

fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(usersData => {

        usersData.forEach((user, index) => {
            let userInfo = document.createElement('h2');
            userInfo.innerHTML = `${user.email} - ${user.name}`;
            userDiv.appendChild(userInfo);

        })
    });
<div id="users">
</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

Angular - Dividing Values within Input Arrays

In the input field available to users, they can enter multiple inputs separated by commas. <div class="container"> Enter your values:<input type="text" multiple #inputCheck> <input type="submit"(cli ...

What is preventing my for loop from reaching the initial index in this visually distinct nested array pattern?

Struggling with rearranging letters in a W shape using arrays. My code seemed to go down instead of reaching level 0. Code snippet: const row = totalLevel =>{ let array = [] for(let i =0;i<totalLevel;i++){ array.push([]) } r ...

Having trouble with PHP not receiving data when using a $.ajax POST request?

I'm facing an issue where my code seems to be correctly passing a JavaScript variable to PHP. On the JavaScript side, everything works fine - I receive success messages and see the data in the network tab. However, on the PHP side, I am unable to retr ...

Storing information from a table into LocalStorage

$('.new_customer').click(function () { var table = $("table"); var number = table.find('tr').length; table.append('<tr id="' + number + '"><td><input type="button" class="btn btn-success btn-xs" ...

Identify the moment when the SPAN element reappears in sight

I have a question that may have been asked before, but I haven't found a satisfactory answer yet. Within my HTML code, I have a SPAN element with an onclick event, like so: <span onclick='loadDiv()'>Text</span> When a user cli ...

JavaScript allows for the creation of animated or timed text

Here is the code snippet I am currently working with: function list() { return "blob1<br>blob2<br>blob3"; } When I run this code, it simply displays all the text in return at once when the function is called. I am wondering if there is a ...

I must create text that is transparent against a colorful gradient background

Hey there! I'm seeking help in figuring out how the text on this site is designed. You can take a look at it here. Essentially, what I'm aiming for is to have the text color match the gradient of the background color from the previous div, while ...

What is the process for accessing a URL using a web browser and receiving a plain text file instead of HTML code?

Hello there! I've created a simple HTML file located at that can display your public IP address. If you take a look at the code of the page, you'll notice that it's just plain HTML - nothing fancy! However, I'm aiming for something mo ...

Collapse the nested child element within when the parent container is expanded/animated downwards

I'm trying to achieve a specific effect where, when the main parent div is toggled or slides down, the child div within it should also hide. Currently, I have a parent div that toggles to display a child div. When I click on a link within the child d ...

How can you determine if a string includes all the words listed in a multidimensional array?

I'm brand new to the world of coding but I have a specific goal in mind. Here's an example of the multidimensional array I'm working with: var requiredProducts = [{ product: 'PRODUCT 1', keywords: ['KEYWORD1', & ...

Having trouble resolving "react-native-screens" from "node_modules eact-navigation-stacklibmoduleviewsStackViewStackViewCard.js"? Here's how to fix it

Here is the command I used for setting up react app routes: npm i react-native-router-flux --save After restarting npm with "npm start," I encountered this error message: Unable to resolve "react-native-screens" from "node_modules\react-navigation- ...

Experiencing a 404 error when trying to fetch JSON data from an external site in WordPress through AJAX, and struggling to display

I am encountering a problem when attempting to access an external website via ajax. When I try to access it, a 404 error occurs preventing me from storing the name parameter data and displaying it on my datatable. Here is one of the error messages displaye ...

Is there a decrease in performance when interacting with variables in the method below?

Alright, I have a reference to a div stored in a variable, which I'll refer to as div_var. Now, when I want to apply some action to it, I have two options for referencing it: div_var.animate()...... $(div_var).animate()..... The first method is mor ...

Create a CSV document using information from a JSON dataset

My main goal is to create a CSV file from the JSON object retrieved through an Ajax request, The JSON data I receive represents all the entries from a form : https://i.sstatic.net/4fwh2.png I already have a working solution for extracting one field valu ...

Enhance your live table previews with the power of React JS

I'm trying to optimize the process of live updating a table in React. Currently, I am using setInterval which sends unnecessary requests to the server. Is there a more efficient way to achieve this without overwhelming the server with these unnecessar ...

What is the best approach for finding the xPath of this specific element?

Take a look at this website Link I'm trying to capture the popup message on this site, but I can't seem to find the element for it in the code. Any ideas? ...

Do discrepancies exist between ' and " symbols?

Similar Question: When to Use Double or Single Quotes in JavaScript Difference between single quotes and double quotes in Javascript I scoured this site and did some internet sleuthing (in that order...) trying to find the answer to this burning q ...

Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with: <script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16. ...

How can `${}` be utilized within Angular applications?

Within TypeScript component files in Angular projects, I often come across this particular syntax enclosed in backticks: <div ${selector} [inDemo]="false" [config]="demoConfig">Demo Content</div> I'm curious about the purpose of the ${} ...

"Enhance your Angular JS experience with dynamic URL parameters and personalized redirection for improved URL accessibility

I'm struggling to make this code function properly: ..... .when('/channel/:id/:slug',{ templateUrl:'views/channel/index.html', controller:'Channel', publicAccess:true, ...