T
TanStack9mo ago
equal-jade

Using useInfiniteQuery to gather all pages

I have a case (at day-job) where we have an API that uses pagination. In most cases, we just use the pagination as-is, using useInfiniteQuery. However, we also have a case where we need to fetch all pages of data "in bulk". That is, if there are 5 pages in total I need to be able to get all 5 before returning data to the application. Each request requires a "token" parameter that comes from the previous page's response. I understand how to get that via getNextPageParam, and I know that the hook's return object includes a function called fetchNextPage. But the examples I've seen in the docs all assume that the app only wants one page at a time and only gets the next page based on an event from the user (button click, etc.). Is this possible, with this particular hook? I wrote a custom hook that uses queryClient.fetchQuery(...) in a loop. It works, but it doesn't update either after the data becomes stale or after the cache is forcibly cleared with invalidateQueries().
1 Reply
robust-apricot
robust-apricot9mo ago
You could fetchNextPage whenever the data.length changes in a useEffect until hasNextPage is false - that would also be the flag that tells you if you can show the data to the user

Did you find this page helpful?