Custom hook in Typescript - Generics and Type #3588
-
I am trying to write a custom hook that can download data from different endpoints and the Query Function will be passed when we call this hook, in typescript what would be the correct way of doing this? All the examples I find define Query function within the hook or have it somewhere and not passed to the hook. Hook Signature:
Custom Hook:
Is this the correct way of defining types for key and query function? Can I import types from react-query and use them like this? The benefit of this approach |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
in your example,
if you want to create low level abstractions, you have to deal with lots of generics ( I also have a twitter thread on the topic if you really want to do something generically in your low-level wrapper: https://twitter.com/TkDodo/status/1491451513264574501 |
Beta Was this translation helpful? Give feedback.
in your example,
useGetData
is exactly the same asuseQuery
, so I don't see any advantages to this approach:if you want to create low level abstractions, you have to deal with lots of generics (
useQuery
takes 4 generics). You can read more about them in my blog: https://tkdodo.eu/blog/react-query-and-type-script#the-four-genericsI also have a twitter thread on the topic if you really want to do something generically in your low-level wrapper: https://twitter.com/TkDodo/status/1491451513264574501