I have implemented infinite scroll on a project that is using React Query library.
So far so good. Everything works as expected using the useInfiniteScroll
hook
One issue that I am encountering is the caching mechanism of this library.
If I query for a resource, ex: GET /posts/
, will trigger a GET /posts/?page=0
, scroll a bit down, get the next results, GET /posts/?page=1
which is totally fine. If I add search parameter to the page will do a GET /posts/?filter=someValue&page=0
. All fine... but when I remove the filter
from the search it will automatically do GET /posts/?page=0
& GET /posts/?page=1
A solution is to remove the query from the cache using the remove()
method from the query itself. But this means that I have to manually do it for each query.
I would like to get a better solution that will cover all cases. I have a queryWrapper where I want to handle this.
I tried using the queryClient instances invalidateQueries
and resetQueries
but none seems to be able to remove it from the cache...
In the examples below I keep a ref
for the params, if they are changed I can trigger the query to reset via useLayoutEffect
hook. This part works as expected
invalidateQueries attempt
queryClient.invalidateQueries(
[queryKey, JSON.stringify(paramsRef.current)],
{
exact: true,
refetchActive: false,
refetchInactive: false
},
{ cancelRefetch: true }
);
resetQueries attempt
queryClient
.resetQueries([queryKey, JSON.stringify(paramsRef.current)], {
refetchPage: (page, index) => index === 0
})
I even tried the queryClient.clear()
method which should remove all existing queries from the cache but still the page number somehow remains cached... I access the queryClient using useQueryClient
hook. If I inspect it, I can see the queries inside.
Can someone please help me to sort this cache issue Thanks!
get-pages
. I scroll to page 2, get page 2 results. I add a filter param, the query key gets one morefilter=a
. When I remove the filter, the query key goes back toget-pages
and automatically gets page 1 and page 2 (because it's cached). My desire is to fetch only page 1.staleTime
keeps the result which is not what I need. – Alto