Reputation: 193
React Pagination and multiple Axios calls
I am trying to map through an array of numbers and make an api call for each one sequentially. However, the api i'm calling has paginated results, so I'm having to run 'function 2' multiple times with the 'next' cursor appended.
My issue is, I'm not able to get the entire functionality to wait until there's no more paginated results before moving onto the next array item in the loop.
Below is my code currently:-
function1() {
let arr = ['837493000', '837493001'];
Promise.all(arr.map((num) => this.function2(num))).then(() => {
this.function3();
});
}
function2(number, after) {
let api = `https://test-api.local/${number}?client_id=123456789`;
if(after){
api = `https://test-api.local/${number}?client_id=123456789&cursor=${after}`;
}
const result = axios.get(api, {
method: 'get',
headers: {
'Client-ID': '123456789'
}
})
.then((response) => response.data)
.then((responseText) => {
if(responseText){
let data = responseText.comments;
if(responseText._after){
this.function2(number, responseText._after);
}
return data;
}
});
}
function3() {
console.log('I ran');
}
componentDidMount(){
this.function1();
}
It is running the first 2 numbers in the sequence and then calling function 3.. Been stumped for hours.. Any help would be appreciated. Thanks
Upvotes: 0
Views: 884
Reputation: 138447
If you return the result from calling function2
(a promise), the promise returned by the function2
it gets returned in gets chained to it:
if(responseText._after){
return this.function2(number, after)
.then(others => [data, ...others]);
}
return [data];
Upvotes: 1