Reputation: 1663
I am hitting an endpoint that gives me a list of users but the result is paginated. The response contains a flag hasMore
which tells if there are more users to be retrieved and an offset
to make the next api call with.
Right now I am able to make multiple calls by manually checking if the result hasMore
is true. How do wrap this logic in a while loop?
function getUsers() {
let users = [];
axios.get(url)
.then(res => {
res.users.forEach(user => {
users.push(user);
})
if (res.hasMore) {
return axios.get(url + '&offset=' + res.offset)
}
})
.then(res => // repeat what I've just done and keep checking hasMore
// How do I check this in a while?
}
Upvotes: 1
Views: 1013
Reputation: 20574
can you move the users = []
up a level?
let users = [];
function getUsers(url) {
axios
.get(url)
.then(res => {
res.users.forEach(user => {
users.push(user);
})
if (res.hasMore) {
getUsers(url + '&offset=' + res.offset);
}
})
.catch(err => {...});
}
Upvotes: 2