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])
});
CodePudding user response:
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
CodePudding user response:
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.