[Typescript] How to correctly type custom hook with useMutation #2816
-
Is this correct? I want to type the options param of my hook and this is the only way I've been able to get it to type properly, but it seems awfully verbose.
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
by typing them all to The generics are:
so, for most cases, this should work:
omitting the key and the fn is good because you statically provide that. but all in all, I would rarely create abstractions that allow for all the options to be passed on consumers side. onSuccess / onError / onSettled can also be used with I've described that separation a little bit here: https://tkdodo.eu/blog/mastering-mutations-in-react-query#some-callbacks-might-not-fire |
Beta Was this translation helpful? Give feedback.
by typing them all to
unknown
, you'll likely have a hard time using e.g. thecontext
or the returned data / error with correct types.The generics are:
TData = unknown
: The type of data, in your case, whatApi.locations.create
returnsTError = unknown
: The type of error that is thrown, unknown is most correct here, but you can also narrow it to AxiosError or so if you're using that.TVariables = void
: The variables passed,ILocationPayload
in your case.TContext = unknown
:context
is used for optimistic updates and is usually inferred from the return value ofonMutate
. Since you let the users of your custom hook specify onMutate, you can't use that without explicitly using a generic.so…