T
TanStack•3y ago
other-emerald

Having difficult using useQuery with generics

Hi everyone, I'm pretty new to Typescript and I'm trying to get generics working with @tanstack/react-query useQuery hook. At the moment I have a hook which has a generic which is passed to the useQuery, however, I'm getting a weird type error related to the "queryKey" property. Does anyone have examples of Typescript generics working with React-Query custom hooks ? I'm struggling to understand where I'm going wrong. I might be making any obvious typescript error as I haven't got to the "generics" part of Total Typescript just yet, so sorry if it's an obvious error. Any comments are greatly appreciated 😄 Thank's, Alex M
No description
2 Replies
correct-apricot
correct-apricot•3y ago
the problem with low-level abstractions is that they are hard to build, because you have to account for all generics, similar to how we do it in useBaseQuery I usually advise users to not build those abstractions, but rather concrete ones, like useTodos and useIssueList that call useQuery directly
other-emerald
other-emeraldOP•3y ago
Hey @TkDodo 🔮 👋 I usually do this on most projects or something like it as often there is a few places in projects where pagination is used, just wanted to consolidate it all into one hook. I actually ended up missing something obvious, I was missing typescripts ReturnType util, heres what I cam up with it includes two approaches https://gist.github.com/AlexMachin1997/6462731447b82eaf15575043184151e0
Gist
A.ts uses generics without inferring from a utility function respon...
A.ts uses generics without inferring from a utility function response. B.ts uses generics with infering the result from the newResource utility function response. - A.ts

Did you find this page helpful?