Search code examples
reactjsinfinite-scrollreact-querytanstack

How to pass direction to the query function when implementing bi-directional infinite list with React Query?


I'm implementing a bi-directional infinite list using useInfiniteQuery from React Query, based on the docs. 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).


Solution

  • There's the assumption that the backend can deliver two cursors, one for forward pagination and one for backward, and that getNextPageParam and getPreviousPageParam will then be able to calculate one pageParam correctly.

    However, if your backend requires to different params, like before=... or after=..., then you'd need access to the fetch direction. We've added this in v5, because we've made substantial improvements to infinite queries there (currently in alpha): https://tanstack.com/query/v5/docs/react/guides/query-functions#queryfunctioncontext