admin管理员组文章数量:1410674
I'm writing a function in Javascript that makes a fetch and receives results that are paginated (as expected, the results are long).
The results will contain a "next_page" which is the fetch home url for the next page of results.Ideally I would like to loop and constantly fetch until I reach the end of the results aka when "next_page" = null.
I can't seem to figure out how to loop through the results while next_page isn't null. What seems to happen is I get stuck in an infinite while loop.
Any suggestions wele. I've provided pseudo code below.
while(next_page!=null){
fetch(apiUrl)
.then(res=>res.json())
.then(data => {
apiUrl=data["next_page]
}
if(apiUrl == null)
{
res.send(data)
break;
}
}
I was thinking the while loop would let me iterate until there was no next_page (aka when it's null). Seems like it's just infinite looping without ever hitting the fetch because the apiUrl doesn't get set to null.
I'm writing a function in Javascript that makes a fetch and receives results that are paginated (as expected, the results are long).
The results will contain a "next_page" which is the fetch home url for the next page of results.Ideally I would like to loop and constantly fetch until I reach the end of the results aka when "next_page" = null.
I can't seem to figure out how to loop through the results while next_page isn't null. What seems to happen is I get stuck in an infinite while loop.
Any suggestions wele. I've provided pseudo code below.
while(next_page!=null){
fetch(apiUrl)
.then(res=>res.json())
.then(data => {
apiUrl=data["next_page]
}
if(apiUrl == null)
{
res.send(data)
break;
}
}
I was thinking the while loop would let me iterate until there was no next_page (aka when it's null). Seems like it's just infinite looping without ever hitting the fetch because the apiUrl doesn't get set to null.
Share Improve this question asked Nov 7, 2019 at 3:44 ASDFASDF 211 silver badge4 bronze badges3 Answers
Reset to default 5You can try below function, instead of while loop
// Initial API Call
fetchData('http://localhost/test1.php?page=1');
// Create the function for API Call
function fetchData(apiUrl){
fetch(apiUrl)
.then(res=>res.json())
.then(data => {
console.log(data);
apiUrl = data['next_page'];
// Check next API url is empty or not, if not empty call the above function
if(apiUrl != '' && apiUrl != null){
fetchData(apiUrl);
}
})
}
This is probably because you're reading data["next_page"]
to apiUrl
, but then checking a different variable in the loop. Should be while(apiUrl) { ...
instead.
Following is loop fetch function, one can name it better though, this can be used in case there is not much logic at the backend side for next page.
const loopFetch = (previousResponse, fetchReq, limit, offset = 0) =>
new Promise((resolve) => {
fetchReq(`&offset=${offset}&limit=${limit}`)
.then((response) => {
const allResponses = [...previousResponse, ...response];
if (response.total === limit) {
// above if condition states logic to check if there is next page
// in my case it was checking limit and total records of response
resolve(loopFetch(allResponses, fetchReq, limit, offset + limit)); // this will resolve previous promise with new loop promise and with all the previous data
}
else resolve(allResponses);
// in case there is nothing more to fetch, else will resolve with all the responses.
})
.catch((err) => {
console.log({ err });
resolve(previousResponse);
// in case of error, resolving all the data that was fetched, can do more handling here (have'nt thought through here)
});
});
Calling the loop fetch API:
const defaultAPILimit = 10;
const headers = {
headers: {
Accept: "application/json",
},
};
const fetchReq = (urlToAttach) =>
fetch("http://dummyURL/?module=xyz" + urlToAttach, headers).then((response) => response.json());
loopFetch([], fetchReq, defaultAPILimit)
.then(() => {
//do something after we have all the responses i.e. after pagination is pleted.
})
.catch((error) => {
console.log(error);
});
本文标签: reactjsIterate through Paginated API Results in JavascriptStack Overflow
版权声明:本文标题:reactjs - Iterate through Paginated API Results in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744955373a2634324.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论