Is there a way to provide fallback onError
handler, which doesn't get called when onError
option is passed to mutate
call?
#3013
-
First of all, thanks for the great lib. I'm trying to provide default mutation error handler for my colleagues. Of course, there must be cases when the devs want to handle the error themselves and do not want the fallback handler, so I'd like to provide the default handler, yet make it work only when the dev did not provide the custom From documentation, I figured So I configured my client as below to see how it works, triggered dummy mutation, and the messages logged just as expected. const queryClient = new QueryClient({
mutationCache: new MutationCache({
onError: () => {
console.log('FROM MUTATION CACHE');
},
}),
defaultOptions: {
mutations: {
onError: () => {
console.log('FROM GLOBAL HANDLER');
},
},
},
});
const { mutate } = useMutation('abc', {
mutationFn: (_: any) => {
throw new Error('error');
},
});
mutate();
// FROM MUTATION CACHE
// FROM GLOBAL HANDLER When I passed const { mutate } = useMutation('abc', {
mutationFn: (_: any) => {
throw new Error('error');
},
onError: () => {
console.log('FROM DEFINITION SITE');
},
});
mutate();
// FROM MUTATION CACHE
// FROM DEFINITION SITE However, when I passed const { mutate } = useMutation('abc', {
mutationFn: (_: any) => {
throw new Error('error');
},
});
mutate(null, {
onError: () => {
console.log('FROM CALL SITE');
},
})
// FROM MUTATION CACHE
// FROM GLOBAL HANDLER <-- 🤔
// FROM CALL SITE Even though I passed (somewhat) custom So my question is...
Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
Yes. There are basically 3 layers of callbacks:
When you set the The callbacks 2) and 3) have different use-cases, which I have outlined here: https://tkdodo.eu/blog/mastering-mutations-in-react-query#some-callbacks-might-not-fire |
Beta Was this translation helpful? Give feedback.
-
@TkDodo Thanks for the quick answer! I'm still curious about my second question. As the behavior of the default handler I'm trying to provide is to simply show the API error message as toast, it seems to belong to
I guess I could make it work. Unfortunately, neither of those exists for now AFAIU. Am I correct? If so, is react-query team open to PRs implementing either of those? I'm willing to try to tackle on this if the team agrees. (if you could point me where I should start that would be awesome) Thanks again in advance. |
Beta Was this translation helpful? Give feedback.
-
To me, this belongs to |
Beta Was this translation helpful? Give feedback.
To me, this belongs to
1
- the cache level callback: https://tkdodo.eu/blog/react-query-error-handling#showing-error-notifications