You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
infinite loop refetch when call window.alert inside request #2868
Describe the bug
Since refetchOnWindowFocus is set to true by default, then if you call window.alert inside a request or somewhere else, you get an infinite loop
It makes sense that it created an infinite loop in your case, because what is happening is that:
Component mounts and useQuery called.
useQuery fires the queryFn (with refetchOnWindowFocus true by default).
queryFn calls window.alert, which causes blur on window (by blur I mean the opposite of focus 👀).
That blur (from step 2) is then dismissed when you click on the button on the alert prompt, which then causes another window focus (as in you are now focusing back on the screen and not on the alert prompt), and we go back to step 2.
What I suggest (And I'm sorry if it might sound too obvious to you) is not to use alerts in the queryFn, but in the onSuccess, onSettled or onMutate.
I agree with @McLovin77 , but I don't think that the situation would be better with the callbacks. Yes, generally, it is better to put side-effects like showing alerts there, however, with the default staleTime of 0, you would still get another refetch because of the focus event.
You can:
turn off refetchOnWindowFocus to avoid the refetch altogether
set a higher staleTime, because only stale queries will be refetched
not use window.alert but a toast library like react-hot-toast
Activity
McLovin77 commentedon Nov 4, 2021
It makes sense that it created an infinite loop in your case, because what is happening is that:
What I suggest (And I'm sorry if it might sound too obvious to you) is not to use alerts in the queryFn, but in the onSuccess, onSettled or onMutate.
TkDodo commentedon Nov 6, 2021
I agree with @McLovin77 , but I don't think that the situation would be better with the callbacks. Yes, generally, it is better to put side-effects like showing alerts there, however, with the default staleTime of 0, you would still get another refetch because of the focus event.
You can:
refetchOnWindowFocusto avoid the refetch altogetherstaleTime, because only stale queries will be refetchedwindow.alertbut a toast library like react-hot-toastI would go with number 3 :)
s-r-x commentedon Apr 13, 2022
facing the same issue. i have a little abstraction over useMutation, that relies on window.confirm. it looks something like this
was able to fix it with these lines
hope it helps