NotZelda
NotZelda16h ago

How to define per route staleTime on queryClient?

It looks like I am unable to override the default stale time provided to react query client, no matter how I define the the route. Is TRPC overriting these dafult somewhere down the chain?
export const createQueryClient = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 1000 * 60 * 30,
},
dehydrate: {
serializeData: SuperJSON.serialize,
shouldDehydrateQuery: (query) =>
defaultShouldDehydrateQuery(query) ||
query.state.status === "pending",
},
hydrate: {
deserializeData: SuperJSON.deserialize,
},
},
});

queryClient.setQueryDefaults(["performanceMetrics", "getEmployeeMetrics"], {
staleTime: Infinity,
});

return queryClient;
};
export const createQueryClient = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 1000 * 60 * 30,
},
dehydrate: {
serializeData: SuperJSON.serialize,
shouldDehydrateQuery: (query) =>
defaultShouldDehydrateQuery(query) ||
query.state.status === "pending",
},
hydrate: {
deserializeData: SuperJSON.deserialize,
},
},
});

queryClient.setQueryDefaults(["performanceMetrics", "getEmployeeMetrics"], {
staleTime: Infinity,
});

return queryClient;
};
By creating the queryClient in this way, I would expect the api route: api.performanceMetrics.getEmployeeMetrics to have an infinite stale time, but it still coming in with the default 30 seconds. I would like to avoid having to wrap every route with my own definition of staleTime, however I also want to make sure no matter why I call these hooks in my app they all have the same staleTime.
3 Replies
Nick
Nick15h ago
Can be passed directly to useQuery and its equivalents
NotZelda
NotZeldaOP13h ago
This is correct, but lets say I have 2 components that call the same API route on the same page. Use query will de-dupe this using the queryKey, however its indeterminate which is will take on as the staleTime. I would rather just declare the staleTime once on the procedure and then not have to make sure all my staleTimes are the same for each useQuery hook using the API.
Nick
Nick11h ago
This is a really a request for the tanstack team I think, rather than us setting up configs for a query key is an interesting idea But you can also just wrap the hook in useMyQuery() and centralise the config

Did you find this page helpful?