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])
});
2
Answers
If you look closely, the
response
is not an array. You’re actually receiving an object with the following structure:So you want to access
response.data
Your response is not an array.
map()
will not work on it. Neither will data[0]. It seems you meant to doresponse.data.map((user) => user.id)
.If you still just want to get the first response, then you can use the same
data[0]
you were using before.