'How to merge all `page.items` from `useInfiniteQuery` data.pages hook into a single array?

When using useInfiniteQuery hook from react-query, we get the data as the object below:

https://react-query.tanstack.com/guides/infinite-queries

enter image description here

Basically we get multiple pages inside the data.pages property, which is an array of pages.

Each page has an items property that contains the array of result items.

I need to merge all those pages[i].items in a single array. And I can't be sure upfront how many pages have been fetched.

What is the best practice/pattern for this?

Is this the way to go?

const allItems = ([] as Array<ItemType>).concat(...data.pages.map((page) => page.items));


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source