T
TanStack11mo ago
generous-apricot

Is it possible to set default queryKey for all queries?

Hello) Has anyone ever needed to set a default queryKey that applies to all queries? In my project, I send the user's language with most queries to receive translations based on it. I want to refetch the query whenever the user changes the app language. Of course, I could add the language as a queryKey for each individual query, but is there a way to set this as a default for all queries? Thanks!
4 Replies
wise-white
wise-white11mo ago
I think what you're after is queryKeyHashFn so you can prefix all your queryKeys with the language. So overriding that and still using their hashKey function you'd have something like:
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryKeyHashFn: (queryKey): string => hashKey([language, ...queryKey])
}
}
})
const queryClient = new QueryClient({
defaultOptions: {
queries: {
queryKeyHashFn: (queryKey): string => hashKey([language, ...queryKey])
}
}
})
wise-white
wise-white11mo ago
Actually, I thought this was how someone solved this in the past but the keys I see in the dev tools don't match. A queryKeyFactory might be the way to go: https://tanstack.com/query/latest/docs/framework/react/community/community-projects#query-key-factory
TanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.
From An unknown user
From An unknown user
No description
conscious-sapphire
conscious-sapphire11mo ago
Implement a global queryKeyHashFn and prepend it there
generous-apricot
generous-apricotOP11mo ago
Thank you guys. Seems that is what I needed)

Did you find this page helpful?