useQuery
callbacks don't run after unmount, useMutation
callbacks do
#5133
-
It seems that the https://codesandbox.io/s/react-query-unmount-req3pu I can see use cases for either behavior. Perhaps there should be some kind of option, and make both of them work the same way by default for consistency? Regardless, what's a good work around for doing an "unmount" cleanup action on a const { data } = useQuery({
queryKey: ["analyze"],
queryFn: () => {
notification("Analyzing");
return analyze(...blahblahblah);
},
onSuccess: () => clearNotification(),
onError: () => notification("Error analyzing"),
}); I want to clear the notification (associated with this query) when the current component, which it is logically associated with, unmounts, because it will no longer be relevant to the user. But the callbacks don't fire if the user navigates away or otherwise unmounts the component while My solution right now is to just use React's useEffect(() => {
return () => {
clearNotification();
};
}, []); But with React 18's double mounting-unmounting, I guess this isn't ideal. Is a more RQ idiomatic way to do this? Could |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
For global callbacks, you'd want the global cache level callbacks, because, again, the callbacks on |
Beta Was this translation helpful? Give feedback.
-
Hi! We had a similar problem where we pass callbacks to the And to be honest I think it's a bit of a weird behavior that when the component that triggers the mutation is unmounted the rest of the logic after the mutation is done, i.e. the callbacks, is swallowed and magically disappears 🤔 What do you think? |
Beta Was this translation helpful? Give feedback.
useQuery
callbacks are observer level callbacks, so they are the same as callbacks on.mutate
. They are thus bound to the lifecycle of components they are mounted in.useMutation
callbacks are the "exception" here, because they always run.For global callbacks, you'd want the global cache level callbacks, because, again, the callbacks on
useQuery
are observer level callbacks, which means if you calluseQuery
twice (e.g. via a custom hook),onSuccess
will also be called twice, showing two notification.