T
TanStack9mo ago
like-gold

Best way to globally handle query keys?

I have a use case where the presence of certain query params in the current url need to be added to all outgoing requests. ex. current url = "www.foo.com?bar=1". "bar=1" would be added as query params to all outgoing requests. "bar" would of course need to be added to the queryKey when calling useQuery(). Does RQ provide a way to configure this globally? Another approach would be for all consumers of useQuery() to call a shared util like "addUrlQueryParams()" when forming the query key. where addUrlQueryParams() is something like:
function addUrlQueryParams(queryKey = []) {
return queryKey.concat( add current url query params here... );
}
function addUrlQueryParams(queryKey = []) {
return queryKey.concat( add current url query params here... );
}
2 Replies
like-gold
like-gold9mo ago
how about use this library? https://github.com/lukemorales/query-key-factory it's really useful manage your queryKey. I think this will solve your problem.
GitHub
GitHub - lukemorales/query-key-factory: A library for creating type...
A library for creating typesafe standardized query keys, useful for cache management in @tanstack/query - lukemorales/query-key-factory
quickest-silver
quickest-silver9mo ago
You can also create a simple function with queryOptions as well https://tkdodo.eu/blog/the-query-options-api . You can combine it with query-key-factory as well.
The Query Options API
v5 brought a new, powerful API, especially if you're using React Query with TypeScript...

Did you find this page helpful?