arta
arta

Reputation: 25

Accessing items with fetch api

I want to access the list of users in an API using fetch and async/await and display them in my html page.

I receive the object and I want to access the items using

I receive the object and I want to access the items using map.

But I get this error:

Uncaught (in promise) TypeError: response.map is not a function

I tried this:

async function getData() {
    let response = await ((await fetch("https://reqres.in/api/users?page=1")).json());
    
    return response.map(user => {user.id;});
}
getData()
    .then(data => {
        console.log(data[0])
    });

Upvotes: 0

Views: 379

Answers (2)

andrilla
andrilla

Reputation: 731

Your response is not an array. map() will not work on it. Neither will data[0]. It seems you meant to do response.data.map((user) => user.id).

async function getData() {
  
  const response = await ((await fetch("https://reqres.in/api/users?page=1")).json())

  return response.data.map((user) => user.id)
}

getData()
  .then(data => {
    console.log(data)
  })

If you still just want to get the first response, then you can use the same data[0] you were using before.

Upvotes: 0

Marius Potor
Marius Potor

Reputation: 11

If you look closely, the response is not an array. You're actually receiving an object with the following structure:

{
  page: 1,
  per_page: 6,
  total: 12,
  total_pages: 2,
  data: [...]
}

So you want to access response.data

Upvotes: 1

Related Questions