T
TanStack•3y ago
manual-pink

Implementation of bi-directional cursor-based pagination

I'm implementing a bi-directional infinite list using useInfiniteQuery, based on the docs (https://tanstack.com/query/v4/docs/react/guides/infinite-queries#what-if-i-want-to-implement-a-bi-directional-infinite-list). The only parameter that gets passed to the queryFn is an object containing the page parameter (one of the two cursors). It's not quite clear to me, in this case, how I can make my backend aware of the direction of the query (i.e. whether I want to get the records after or before the given cursor value). What would be the recommended way to implement this?
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:
6 Replies
deep-jade
deep-jade•3y ago
usually, there is only one cursor param that you pass to the api endpoint, like we do in our example: https://tanstack.com/query/v4/docs/react/examples/react/load-more-infinite-scroll the backend computes next and previous cursors depending on that
React Query Load More Infinite Scroll Example | TanStack Query Docs
An example showing how to implement Load More Infinite Scroll in React Query
deep-jade
deep-jade•3y ago
but yeah, if your API needs like a ?before= or ?after= param, we would actually have to pass the fetchDirection into the queryFn, which we are not currently doing
manual-pink
manual-pinkOP•3y ago
@TkDodo 🔮 On the backend I have a regular MySQL table with a sequential id column that serves as a cursor. I access it through prisma, so to move backwards I need to pass a negative value to take (https://www.prisma.io/docs/concepts/components/prisma-client/pagination#example-paging-backwards-with-cursor-based-pagination). The problem is how do I know when to pass a negative value. Thanks for confirming that this is not supported out of the box (although I must say I'm a bit surprised, as it seems a fairly common use case).
Prisma
Pagination (Reference)
Prisma Client supports both offset pagination and cursor-based pagination. Learn more about the pros and cons of different pagination approaches and how to implement them.
deep-jade
deep-jade•3y ago
I'll probably add this in v5
manual-pink
manual-pinkOP•3y ago
@TkDodo 🔮 hey, that looks good! Thanks for adding it so fast! 🙂

Did you find this page helpful?