T
TanStack•2y ago
exotic-emerald

How do I create a resuable composable for a mutation?

Thanks for this great library. I have a mutation that I want to reuse in multiple places, but I'm having trouble typing the options in the composable that I want to create e.g
export const useSaveUser = (options: MutationObserverOptions) => {
return useMutation({
mutationFn: saveUser,
onSuccess: opts.onSuccess,
onError: opts.onError,
});
};
export const useSaveUser = (options: MutationObserverOptions) => {
return useMutation({
mutationFn: saveUser,
onSuccess: opts.onSuccess,
onError: opts.onError,
});
};
Can the mutations be re-used this way or is this something that is not intended?
4 Replies
ratty-blush
ratty-blush•2y ago
what are you trying to achieve by customizing onSuccess and onError like that? What would you want to do in different locations? Hint: You might be looking for the callbacks on .mutate
exotic-emerald
exotic-emeraldOP•2y ago
Thanks for replying @TkDodo 🔮 , the same mutation would cause a different side-effect depending on the location that it's used e.g different toast messages, setting different client-side data etc. am I right thinking that it's not intended to abstract mutations in such way?
ratty-blush
ratty-blush•2y ago
you can of course do it, MutationObserverOptions is likely not the right type - but I wouldn't do it. You can make two mutations with the same mutationFn and different callbacks. That's likely better.
exotic-emerald
exotic-emeraldOP•2y ago
@MrMentor maybe you can help figuring out the types for the mutation options?

Did you find this page helpful?