Remove query from cache without refetching react query

HobbitOfShire picture HobbitOfShire · Jan 4, 2021 · Viewed 9.5k times · Source

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?

Answer

TkDodo picture TkDodo · Jan 4, 2021

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?