0

I am trying to loop through all pages of an API result that returns the next page as URL in the result:

enter image description here

            const api_url= 'https://wger.de/api/v2/exercise/?format=json&page=29';

                async function getExercises(){
                    const response = await fetch(api_url);
                    const data = await response.json();
                    data.results.forEach( item => console.log(item.name))
                }
                getExercises();

How would you go around doing this?

CherryDT
  • 25,571
  • 5
  • 49
  • 74
Hi tE
  • 154
  • 10

2 Answers2

1

You can use a while loop:

async function getExercises () {
  let url = 'https://wger.de/api/v2/exercise/?format=json'

  while (url) {
    const res = await fetch(url)
    const data = await res.json()

    for (const item of data.results) {
      console.log(item.name)
    }

    url = data.next
  }
}

// By the way, always catch errors here, otherwise they will become unhandled rejections!
// This is assuming that this call happens outside of an async function.
getExercises().catch(e => console.error('Failed to get exercises', e))

Also, I made an educated guess that you can specify a limit parameter, tested it and it seems it works. So you could decrease the number of requests needed by setting a higher limit, e.g. https://wger.de/api/v2/exercise/?format=json&limit=1000 (right now there are 685 results so with limit 1000 it would even need only one request to get all results, but of course you should still use this code so that it fetches page 2 in case one day there are more than 1000).

CherryDT
  • 25,571
  • 5
  • 49
  • 74
  • I see, i never knew about the limit parameter! Thank you very much for the explenation!! – Hi tE Mar 13 '20 at 22:16
0

You can achieve this using the recursion.

let currentPage = 1;
const limit = 5;
const apiURL = 'https://wger.de/api/v2/exercise?format=json';

const getExercises = async () => {

    const res = await fetch(`${apiURL}&page=${currentPage}`);
    const data = await res.json();

    // you can remove the limit
    if (data.results.length && currentPage <= limit) {
        currentPage++;
        data.results.forEach(val => console.log(val.name));
        getExercises();
    } else {
        return;
    }
}
getExercises();
Phani Mahesh
  • 85
  • 1
  • 13