MutateAsync error handling (callback vs. try/catch/finally)
Is it more appropriate to handle the mutation lifecycle during mutateAsync using the callbacks on useMutation (onSuccess/onError/onSettled) or to use a try/catch/finally to do that?
Right now we're using mutateAsync during a form submission. The problem is it requires a try catch so if an error occurs it doesn't throw an unhandled exception. Some of the devs are catching the error and putting a //noop as a comment and handling errors via tha callbacks and others are handling the lifecycle within the try blocks instead.
Looking to see if anyone has a recommended pattern or if there's a preference so our team can maybe standardize it if possible.
1 Reply
flat-fuchsia•8mo ago
There are pros and cons of each choice.
the callback functions are sort of nice because you can avoid doing try-catch, but it also means that any logic that needs to happen is in a different part of the component.
We tend to use mutateAsync and wrap in try/catch.
I know that a lot of docs/blog articles suggest using the callbacks as the primary choice, (e.g. https://tkdodo.eu/blog/mastering-mutations-in-react-query#mutate-or-mutateasync) - but the framework authors seem to change their preferences over time (e.g. https://tkdodo.eu/blog/the-query-options-api#query-factories
Separating QueryKey from QueryFunction was a mistake
) and what was best practice in prior versions is now completely removed/deprecated in v5.
I would just decide what works best for your team and run with it.