How to get all the results of a paginated REST API?

I have the below JS code to loop through the pages of a paginated rest api. In the for loop I call the API query "AllOrders" with the parameter page. In the console I see that the page is going up from 1 to 7. But if I return the array arrOrders[] than on every page I see back the results of page 1.

const createdAtMin = txtOrdersFromDate.value;
await OrdersCount.trigger({
  additionalScope: { createdAtMin },
});
const totalOrders = OrdersCount.data.count;
const pageLimit = 50;
let page = 1;
let totalPages = Math.ceil(totalOrders / pageLimit);
let arrOrders = [];

console.log("Total pages: " + totalPages);

for (page; page <= totalPages; page++) {

  console.log("Current page: " + page);

  let currentPageData = null;
  
  //fetch data
  await AllOrders.trigger({
    additionalScope: {
      page: page
    },
  });

  currentPageData = AllOrders.data.orders;
  
  //append data
  arrOrders = [...arrOrders, currentPageData];
}

return arrOrders;

Has anyone a clue? I don't get it!

  const dataForPage = await AllOrders.trigger({
    additionalScope: {
      page: page
    },
  });

  const currentPageData = dataForPage.orders;

In these two cases can you try assigning the result of the trigger function to a variable (as shown) and reference that instead of query.data? The React state setter probably isn't done setting query.data by the time you're referencing it but a variable would be set prior to the next line being evaluated.

Thanks @kschirrmacher.

Now my looping is correct and I get all of the orders back. But my query result (return arrOrders) is per page anyway.

I want to display all the orders into a table so I want that the query results in order records only. So if my pageLimit = 50 and I have 60 orders then I don't want that my result is split up like this:

0
order 1
order 2
...
order 50
1
order 51
...
order 60

I want that all the orders are in one big recordset.

order 1
order 2
order 3
...
order 60.

Can you help me with that?

Try return arrOrders.flat().

Yes!!! Thanks @kschirrmacher

1 Like