Typed cache
I was wondering if we could do something like typed "cache".
Kinda like what router does with loaders.
Our app has grown quite a bit and mistakes in form of key collision happen now.
I would like to tie query keys with data type so that mishandling would error in typescript or at least being passed down to the useQuery data type with a union.
In my opinion this would dramatically improve dx.
Especially in cases of optimistic data mutation where setQueryData is used.
The way I'm thinking of implementing it is with a wrapper around useQuery & QueryClient but I don't know if this would benefit from being package level.
Do you think this should be discussed or something of the sort is already being discussed in the github ?
Some related topics :
- https://github.com/TanStack/query/discussions/3888
- https://github.com/TanStack/query/discussions/8123
- https://tkdodo.eu/blog/type-safe-react-query#what-about-getquerydata
But It doesn't go all the way to the QueryClient for validation.
3 Replies
harsh-harlequin•11mo ago
Especially in cases of optimistic data mutation where setQueryData is used.
queryOptions
kinda fixes this: https://tkdodo.eu/blog/the-query-options-apiThe Query Options API
v5 brought a new, powerful API, especially if you're using React Query with TypeScript...
unwilling-turquoiseOP•11mo ago
Yeah ! It looks better than just simple queries but I was thinking of something more akin to query tree like a giant object to generate typed definition as well as having a pattern like what you described in https://tkdodo.eu/blog/the-query-options-api with query factories.
The biggest problem I see is when I use queryClient.getData that has to be typed. I'm using zod as well but I might as well not cause errors in runtime that can be avoided with types.
I can keep this post updated when I'm done with the implementation. I don't know if I'll be able to work on that right away but the idea is there.
The Query Options API
v5 brought a new, powerful API, especially if you're using React Query with TypeScript...
harsh-harlequin•11mo ago
queryClient.getQueryData becomes typed if you pass a key to it that was generated with queryOptions. That's the reason why I said it "fixes that"