Skip to content Skip to sidebar Skip to footer

How Do I Loop Through Multiple Pages In An Api?

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.

Solution 1:

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:

asyncgetData() {
     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;
 }

Solution 2:

You can do it with async/await functions more easily:

asyncfunctionfetchAllPages(url) {
    const data = [];

    do {
        let response = fetch(url);
        url = response.next;
        data.push(...response.results);
    } while ( url );

    return data;
}

This way you can reutilize this function for other api calls.

Post a Comment for "How Do I Loop Through Multiple Pages In An Api?"