Reputation: 153
I am trying to add numbers from 0-99 to myData function so it prints all of my users with one click. But I'm getting an error.
Error: index.js:14 Uncaught (in promise) TypeError: Cannot read property 'userId' of undefined at index.js:14
function number() {
for (let i = 0; i < 100; i++) {
i;
}
}
const myData = () => {
fetch('https://jsonplaceholder.typicode.com/posts?fbclid=IwAR2aHkMfSVPYV3va38MKu-jOahl9G8UzyPJ1Dd67EyskMPZMw1gN9xi-AUg')
.then(response => {
return response.json();
})
.then(users => {
document.getElementById('demo').innerHTML += `
User ID: ${users[number()].userId}<Br>
ID: ${users[number()].id}<br>
Title: ${users[number()].title}<Br>
Desc: ${users[number()].body}`;
})
}
Upvotes: 0
Views: 3782
Reputation: 5601
It's not clear what you hope the number()
function will do. As you have it in the question it will run the for-loop then exit the function with a return value of undefined
. Adding return i
will cause it to return zero and exit the loop immediately.
If your intent is to set the demo
id's innerHTML to have all users, then you need to have the actions within the loop like this:
.then(users => {
let allUsersHtml = "";
for (let i=0; i<users.length; i++) {
allUsersHtml += `
User ID: ${users[i].userId}<br>
ID: ${users[i].id}<br>
Title: ${users[i].title}<br>
Desc: ${users[i].body}`;
}
document.getElementById('demo').innerHTML = allUsersHtml;
})
This assumes that the users
data coming back is an Array
object.
The main problem with your first attempt is in understanding how functions operate. They can only return one thing each time they are called. Just because they include a for-loop doesn't mean they'll cause any repeating in the functions that call them.
Upvotes: 2