Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  116] [ 1]  / answers: 1 / hits: 5585  / 5 Years ago, tue, july 30, 2019, 12:00:00

I am using the Star Wars API https://swapi.co/ I need to pull in starships information, the results for starships span 4 pages, however a get call returns only 10 results per page. How can I iterate over multiple pages and get the info that I need?



I have used the fetch api to GET the first page of starships and then added this array of 10 to my totalResults array, and then created a While loop to check to see if 'next !== null' (next is the next page property in the data, if we were viewing the last page i.e. page 4, then next would be null next = null) So as long as next does not equal null, my While loop code should fetch the data and add it to my totalResults array. I have changed the value of next at the end, but it seems to looping forever and crashing.



function getData() {
let totalResults = [];

fetch('https://swapi.co/api/starships/')
.then( res => res.json())
.then(function (json) {
let starships = json;
totalResults.push(starships.results);
let next = starships.next;

while ( next !== null ) {
fetch(next)
.then( res => res.json() )
.then( function (nextData) {
totalResults.push(nextData.results);
next = nextData.next;
})
}

});
}


Code keeps looping meaning my 'next = nextData.next;' increment does not seem to be working.


More From » while-loop

 Answers
0

You have to await the response in a while loop, otherwise the loop runs synchronously, while the results arrive asynchronously, in other words the while loop runs forever:



  async getData() {
const results = [];
let url = 'https://swapi.co/api/starships/';

do {
const res = await fetch(url);
const data = await res.json();
url = data.next;
results.push(...data.results);
} while(url)

return results;
}

[#6745] Friday, July 26, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leslijessalyng

Total Points: 650
Total Questions: 85
Total Answers: 109

Location: Croatia
Member since Mon, Sep 6, 2021
3 Years ago
leslijessalyng questions
Fri, Feb 21, 20, 00:00, 4 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Wed, Mar 13, 19, 00:00, 5 Years ago
Fri, Dec 14, 18, 00:00, 6 Years ago
;