Default Mutation Function best practices and Typescript
I've set up a default query function per the guide in the docs, but there's no guide on a default mutation function. I'd like to set on up so I don't have to get the auth token in each component, etc. Can I just do the following:
If that's appropriate, how do I resolve the
defaultOptions.mutations.mutationFn
typescript error?
7 Replies
flat-fuchsia•2y ago
You can't type the default mutation function like that because it's not guaranteed in TS that all your mutations will have that input. So either do a type assertion to bypass TS or validate at runtime with e.g. a zod schema
like-goldOP•2y ago
Aren't those types what determines the acceptable inputs for the mutation function? Then if somewhere in my code I pass something that doesn't match, TS will warn me? Apologies, still pretty new to TS.
flat-fuchsia•2y ago
The default mutation function doesn't set the types for all call-sides, no
like-goldOP•2y ago
I appreciate the replies.
So what do people normally do for mutations throughout their app that's behind a JWT? Do they add the header each time they useMutation?
perhaps just use a custom useAxios hook?
Then in my component it's just:
sunny-green•2y ago
What about using https://axios-http.com/docs/config_defaults
like-goldOP•2y ago
Well, since it would need to be configured based on the presence of the token (which changes, either way it'll need a custom hook, right?
flat-fuchsia•2y ago
it's usually best to keep these things out of react-query, on your api layer