Home > Blockchain >  Implement infinite query with traditional backend pagination
Implement infinite query with traditional backend pagination

Time:11-07

I'm developing a react-native application and I want to implement an infinite scrolling list, I've reviewed the infinite query documentation, but I can't figure out how the implementation example can fit with the structure of my backend. On the other hand, it is not clear to me if an infinite query or a paged query fits better in this scenario(implement infinite scrolling).

Current backend structure

Request

https://some-endpoint/search?limit=10&offset=0

With this structure my backend returns:

{
    limit: 10,
    offset: 0,
    totalResults: 300,
    results: [{...results}],
}

Each time the limit of the list scroll is reached, these variables are updated until we reach the total number of results.

offset: offset   limit,

CodePudding user response:

Since your paginated queries depend on offset and limit you can do something like:

const { data, hasNextPage } = useInfiniteQuery(['queryKey'], ({ pageParam = 0 }) => queryFn(pageParam), {
  getNextPageParam: (lastPage) => {
    const totalPages = Math.floor(lastPage.totalResults / lastPage.limit)
    const actualPage = lastPage.offset / lastPage.limit 
    return actualPage < totalPages ? actualPage   1 : undefined // By returning undefined if there are no more pages, hasNextPage boolean will be set to false
  }
})

const queryFn = async (page) => {
  const limit = 10
  const offset = page * limit
  const res = await fetch(`https://some-endpoint/search?limit=${limit}&offset=${offset}`)
  
  ...
}

Explanation:

The first request to the backend will be made with pageParam = 0 by default, therefore, in the queryFn the offset will be calculated to 0 to retrieve the first items from the backend. From what you explain in your post, the backend will also return this offset on each response, which will be used to calculate the actualPage in getNextPageParam.

It goes like:

  1. First request is made with pageParam = 0, the backend's response will contain offset: 0.
  2. getNextPageParam uses this value to calculate the actualPage: offset / limit which equals to 0 / 10, so actualPage will have a value of 0.
  3. Since actualPage < totalPages, then the next page param will be actualPage 1 which equals to 0 1. Next page will now have a value of 1.
  4. This value is passed to your queryFn for the next request, so now the offset will be 10.
  5. The backend's response offset will now be 10.
  6. And so on...

Let me know if that helps.

  • Related