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

3 messages · Page 1 of 1 (latest)

dapper fractal
#

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]);
sullen bladeBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

snow hemlock
#

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.