I am tying to write a recursive function that would keep on fetching some paginated data from an api until it fetches all the data from all the pages.
For example the data from the api return this {"pageCount": 3, "pageNumber": 1} so I want to recursively call the api each time by incrementing the page number until it reaches 3 and then it stops. The issue that I am facing is that the recursive function is being called an additional time even though the condition for the while loop is not met. Here is my code:
let pagecount = 3;
let i = 1;
const testfunc = (page) => {
console.log("apicalled with page", page);
console.log("page", page, "pagecount", pagecount);
if (page === pagecount) {
console.log("condition fulfilled", page !== pagecount);
}
while (page !== pagecount) {
page++;
testfunc(page);
}
};
testfunc(i);
This is the output that I am getting:
apicalled with page 1 page 1 pagecount 3 apicalled with page 2 page 2 pagecount 3 apicalled with page 3 page 3 pagecount 3 condition fulfilled false //Should stop here apicalled with page 3 page 3 pagecount 3 condition fulfilled false