Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove query from cache without refetching react query

I am using react query in my react app this way

    const { data, status } = useQuery(key, queryFunc, { staleTime: 1 * 60 * 1000 });

I want to be able to invalid a certain key in cache based on data value, basically when data is null, so I added an effect

useEffect(() => {
   if (data === null) {
     queryClient. invalidateQueries(key)
   }
}, [data])

This approach will cause a request loop where an invalidated query will refetch, get null as response, effect executes and invalidates and so on so on...

I want to be able to remove the key from cache without refetching, so I don't end up in this infinite requests loop, been digging into the react query docs but no luck. Anyway had a similar case with react query where key needs to be removed from cache without refetch?

like image 863
HobbitOfShire Avatar asked Jan 04 '21 16:01

HobbitOfShire


1 Answers

I think queryClient.removeQueries(key) would do what you want: https://react-query.tanstack.com/reference/QueryClient#queryclientremovequeries

Can you maybe elaborate a bit on your use case? Why would you want to remove a query from the cache if data is null?

like image 126
TkDodo Avatar answered Oct 16 '22 09:10

TkDodo