Fractal
Fractal9mo ago

Mutation on pagehide handler not firing on page refresh, only on page close

I’m trying to make my app fire a mutation when the user closes the tab. As far as I know, the main way to do that nowadays is to use the pagehide event, so I have code like this in a root component.
// Disconnect on close
const disconnect = useMutation(api.lobby.disconnect);
useEffect(() => {
const listener = async () => {
await disconnect(credentials);
};
window.addEventListener("pagehide", listener);
return () => {
window.removeEventListener("pagehide", listener);
};
}, [disconnect, credentials]);
// Disconnect on close
const disconnect = useMutation(api.lobby.disconnect);
useEffect(() => {
const listener = async () => {
await disconnect(credentials);
};
window.addEventListener("pagehide", listener);
return () => {
window.removeEventListener("pagehide", listener);
};
}, [disconnect, credentials]);
This works fine when closing the tab (I can see in the Convex dashboard that the mutation gets fired), but somehow it does not work when refreshing the page: the pagehide event listener does get called but not the mutation itself (I cannot see anything in the Convex dashboard). Any idea why it would behave differently on refresh and closing a tab? And what I can do to fix it? Note that I can’t seem to be able to get any logs or errors after the await disconnect(credentials). It’s probably because a pagehide event listener only runs the synchronous part of the event listener and then closes the page.
1 Reply
Michal Srb
Michal Srb9mo ago
Hmm, I'm not sure how Convex could affect this. This could be some specific browser behavior (refresh doesn't finish the async ticks, while page close does?). What if you replace the mutation call with a fetch to some test API, that way you can see if this is Convex-related.

Did you find this page helpful?