Search code examples
infinite-scrollreact-query

How to achieve Infinite scroll in React with React Query?


I want my API to fetch new data as in increase the page number when I have reached the bottom of the page, basically I want to infinite scroll with React Query.

I have literally watched all the videos out there but am still unable to figure out why isn't it working. Please help me out.

events: (30) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
hasNextPage: true

There's no mention of the number of pages available in this API, or the total number of events available. The only way to check if there is a next page is through this hasNextPage: true property which returns either true or false

So I have no clue on how to do that using React-Query, I have tried multiple approaches. Can anyone please help me out on how to achieve Infinite scroll using React-Query with this data from the API.


Solution

  • You can use the npm package react-infinite-scroll-component along with useInfiniteQuery hook.

    This article demonstrates it in detail.