Next.js Discord

Discord Forum

I can't stop router push when someone have un saved changes

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
here this vid show he can't refresh the page but can go anther page by slidebar i used a router push at it so how i can stop twice router push and refresh


here a code

import { useRouter } from 'next/router';


 const router = useRouter();
  

  const hasUnsavedChanges = CliendSideData.chN !== ServerSideData.chN;

  useEffect(() => {
    const handleBeforeUnload = (event: BeforeUnloadEvent) => {
      if (hasUnsavedChanges) {
        event.preventDefault();
        event.returnValue = '';
      }
    };

    const handleRouteChange = (url: string) => {
      if (hasUnsavedChanges) {
        const confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';
        if (!confirm(confirmationMessage)) {
          router.events.emit('routeChangeError');
          throw `Route change to ${url} was aborted (unsaved changes).`;
        }
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

   
    router.events.on('routeChangeStart', handleRouteChange);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
      router.events.off('routeChangeStart', handleRouteChange);
    };
  }, [hasUnsavedChanges, router]);

2 Replies

Kurilian Bobtail
the only way I found to mitigate this was to wrap <Link adding an onClick guard that confirms navigation if a global dirty flag is set.
and in your case, as you are not using basic <Link but rather useRouter().push wrap that similarly and use the wrapped method.