-1

After request I have response in a body and it looks like [{...}]. In my browser console it is noticed as array. But console.log(users[0]) is interpreted as undefined. Why can't I get the first element of users object?

    async function getUsers() {
    const response = await fetch("/api/users");
    const users = await response.json();
    return users;
}

let users = getUsers();
console.log(users[0]);
console.log(users);
evggenn
  • 23
  • 4

3 Answers3

5

what you get after fetch is a promise

You deal with it asynchronously by using .then

getUsers().then((users) => {
    console.log(users[0]); //returns the user with in the first index
    console.log(users); // returns all users
});
1

getUsers returns Promise, try using then

getUsers().then((users) => {console.log(users[0]);console.log(users);});

Sakil
  • 666
  • 3
  • 8
1

After a fetch you get a promise, which has states like pending, reject, resolve, therefore you get a promise after getUsers, and you can use .then on the returned value

getUsers().then((users) => {
  let users = users
  setUsers(users)
  console.log(users[0]);
  console.log(users);
});

This return the users in a console.

Habeeb Tijani
  • 1
  • 3
  • 14