T
TanStack15mo ago
harsh-harlequin

Specify queryKeyHashFn for queryClient.setQueryData()

It doesn't look like I can set a custom query key serializer with queryClient.setQueryData() https://tanstack.com/query/latest/docs/reference/QueryClient/#queryclientsetquerydata I see that the default options are used, and this is leading me to suggest users of the integration I'm writing to use this global settings. I'm wondering if this is a philosophical thing and I should try to move toward more simply serializeable query keys or if it would make sense to expose this and I should open a PR.
4 Replies
genetic-orange
genetic-orange15mo ago
Sounds like it's that way by design. Multiple queryKeyHashFns could have unintended key conflicts
harsh-harlequin
harsh-harlequinOP15mo ago
I'm specifying it globally for now, I do have e.g. bigints I'd like to hash so I do need a custom hash function but don't always want to take over the whole react-query setup if someone else needs a custom hasher. @troywoy is that your read from the question or based on something else? I think this API would make sense
genetic-orange
genetic-orange15mo ago
I would expect the queryKeyHashFn to have the "one source of truth" ideology. I suppose if you present a good use case and Dominik sees use in it then sure, but I'm just an RQ user
harsh-harlequin
harsh-harlequinOP15mo ago
I'll provide one that detects my specific keys and hashes them my way, accepts a callback middleware-style in case the developer needs another custom hasher, and falls back to the default if not. I found this relevant issue: https://github.com/TanStack/query/issues/4052 It describes setQueryData() not using the custom queryKeyHashFn specified when the query was created as a bug. The discussion concludes that using the initially specified queryKeyHashFn would be too tricky, so
I think if you need a custom queryKeyHashFn, the best thing you can do is: set it as a default, globally, for all queries -TkDodo
That pretty well answers this; the behavior I wanted was the ability to use a custom hash function, not to remember the one that was originally set, but this mentions that too. I didn't know about setQueryDefaults, that could help. If all of my queries started with a given first element I could get behavior for just those with queryClient.setQueryDefaults(['myPrefix'], { queryFn: myFetch, queryKeyHashFn: myQueryKeyHashFn })

Did you find this page helpful?