How react Infinite Queries support with offset and limit

Viewed 2322

I tried to implement an infinite scroll with my react.js project using Infinite Queries in react-query and react-virtual. But Infinite query is supporting with the cursor and the page. and my API is not supported for pages, and it has a limit, offset, and totalCount in the metaData as below

meta: { limit: 100, offset: 0, total: 1000}

Are Infinite Queries support for limit and offset?

There are links that I followed.

https://codesandbox.io/s/github/tannerlinsley/react-virtual/tree/master/examples/infinite-scroll

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

1 Answers

infiniteQueries don't really care how your backend delivers a "cursor" to the next page, it just matters that the backend delivers something.

Basically, whatever is returned from getNextPageParam will be injected into the queryFn as pageParam. Here is an example that might fit your use-case:

const { data } = useInfiniteQuery(
    'key',
    ({ pageParam }) => axios.get(myUrl + '?offset=' + pageParam?.offset ?? 0),
    {
        getNextPageParam: (lastPage) => lastPage?.meta
    }
)

The concept of a "page" is merely what ever your backend returns for a single fetch. So here, on the first fetch (for page 0), we have no pageParam, so we initalize with offset: 0. Then, we fetch with that, and the backend returns the first set of data (a page), and we extract the meta info for it (offset = 20 or whatever).

If you call fetchNextPage(), the queryFn will be called with that meta information, so the next fetch does ?offset=20. The backend delivers offset: 40 as meta and the infinity continues.

Hope that explains it :)

Related