useInfiniteQuery for pagination without page metadata or nextCursor
I have an API which takes in 2 parameters query 'q' and page 'p'. I have infinite scrolling for this API. Whenever page is increased I am appending the next page's response in a state variable with the previous one. And whenever q is changed I reset page 'p' to 1 and the state variable array is reset to new response. I was wondering I could use useInfiniteQuery hook for this but since my API does not give any metadata about next page I am not sure this could be even done. Can anyone share a similar example?
10 Replies
stormy-goldOP•3y ago
How I know that the current page is the last one is when I see an empty array as a response from API, I stop calling further API calls.
gradual-turquoise•3y ago
I think that can work, you can just do this in
getNextPageParam: look at the last page, if empty return undefined, otherwise return lastPage + 1stormy-goldOP•3y ago
The function getNextPageParam has params lastPage and allPages, and these are arrays in my case. How does lastPage+1 work here? Where do I get the current page context from? Should I maintain it in state?
stormy-goldOP•3y ago
This is the current code I have, issue is with
page + 1 line. This, do I have to maintain in a state variable?
stormy-goldOP•3y ago
Oh I think I have an idea in my getSearchResults function instead of directly returning the array I can resturn an object like {data: myArray, nextPage: pageParam + 1} and this pageParam comes from react query
Is this a viable approach?
extended-salmon•3y ago
in v5, getNextPageParam will also have access to the previous pageParam to make this easier
gradual-turquoise•3y ago
Yes, this is how I would do it. Small improvement, return
{data: myArray, nextPage: myArray.length > 0 ? pageParam + 1 : undefined} from getSearchrResults.
Then getNextPageParam becomes:
stormy-goldOP•3y ago
Thanks for the help! It works well now
extended-salmon•3y ago
GitHub
Release v5.0.0-alpha.5 · TanStack/query
Version 5.0.0-alpha.5 - 3/11/2023, 11:56 AM
Changes
Feat
pass pageParams to getNextPageParam (#5090) (cb76da3) by Dominik Dorfmeister
Chore
vitest jest migration cleanup (#5117) (4ebb083) by Zac...
extended-salmon•3y ago
example usage in the docs: https://tanstack.com/query/v5/docs/react/guides/infinite-queries#what-if-my-api-doesnt-return-a-cursor
Infinite Queries | TanStack Query Docs
Rendering lists that can additively "load more" data onto an existing set of data or "infinite scroll" is also a very common UI pattern. TanStack Query supports a useful version of useQuery called useInfiniteQuery for querying these types of lists.
When using useInfiniteQuery, you'll notice a few things are different: