T
TanStack•3y ago
optimistic-gold

Refetching a query with different cache-control headers

Hey, I'm looking for a way to refetch a query with different cache-control headers. Currently I'm caching a response in the browser cache but I would like to be able to bust that cache if needed. However, I haven't figured a way to refetch a query with different headers. At first I tried something like this but I quickly found out it doesn't work as one place will have a query with queryKey ["cars", false] and another will have a query with ["cars", true]:
const useCarsQuery = (cacheBust: boolean) => {
return useQuery({
queryKey: ["cars", cacheBust],
queryFn: async () => {
return await getCars(cacheBust);
},
});
};

const getCars = async (cacheBust: boolean) => {
const headers = cacheBust ? { "Cache-Control": "no-cache" } : undefined;
const response = await fetch(`/cars`, { headers });
return response.json();
};
const useCarsQuery = (cacheBust: boolean) => {
return useQuery({
queryKey: ["cars", cacheBust],
queryFn: async () => {
return await getCars(cacheBust);
},
});
};

const getCars = async (cacheBust: boolean) => {
const headers = cacheBust ? { "Cache-Control": "no-cache" } : undefined;
const response = await fetch(`/cars`, { headers });
return response.json();
};
What would be the best way to refetch the query so that the browser cache gets busted?
2 Replies
optimistic-gold
optimistic-goldOP•3y ago
I managed to get a working solution using queryClient.fetchQuery but it feels a bit hacky. If there is a better way, please let me know!
fascinating-indigo
fascinating-indigo•2y ago
Thanks a lot @Lomant 🫡

Did you find this page helpful?