FractalF
Convex Community2y ago
1 reply
Fractal

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]);


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.
Was this page helpful?