View more and view less button with React query

Viewed 79

In my React app, I have a page that when renders, it makes a fetch request using React Query useInfiniteQuery to get two items from the server and populate a list.

I implemented a "View more" button that when you click on it, it will call React Query useInfiniteQuery, fetch more data and add it to the list. I can do this X times and potentially get hundreds of items in the list.

When there is no more data to fetch I change that button to a "View less" button and when I click on it I want to do some kind of "collapse" and show the fist two items on the list.

How can I achieve this? Is there something that comes with React Query that let's me do this?

Should I just remove the items from the DOM manually?

1 Answers

react-query doesn't do anything dom related, it's up to you how many pages you want to render. if you have 10 pages in the cache and only want to render 2 of them - then only render 2 of them. you can also remove the other pages from the cache with queryClient.setQueryData, but I wouldn't do that.

Related