How to fetch all items using Fetch API?

How to fetch all items using Fetch API?
0.0 0


I am trying to write a function that defines to a variable the number of total items returned. The variable (totalItems) will be used to find the last page of the API (total number of items / limit of responses per page = total number of pages).

My question is: How do you fetch all items at once? Is there a method to do this dynamically that works no matter how many items are at an API endpoint?


Promise.all will take a set of promises passed as an array, and returns a single promise that resolves when they all complete.
For example (this is very rough untested pseudocode, I’m guessing at how the API works as well)

// assuming you pass in an array of the page numbers,
async collectPagedData(arrayOfPageIndices) {
  const promises = pageNo => {
    const req = await fetch(`${pageNo}`);
    return req.json();
  const data = await Promise.all(promises);
  // flatten all of the paged data, i.e.:
  // array of arrays of data -> array of data.
  return data.reduce((a, b) => [...a, ...b], []);


Thank you Dan, I will try this approach out!