Next.js Discord

Discord Forum

Throwing an error on routeChangeStart changes the browser URL

Unanswered
Africanized honey bee posted this in #help-forum
Open in Discord
Africanized honey beeOP
Hello,

I'm trying to show an alert box if the user tries to navigate to another page without saving a form. I'm using Router.events.on("routeChangeStart", routeChangeStart); where routeChangeStart() throws an error if the user clicks cancel on the alert box; everything works fine - the user is not taken to another page. However, the URL in the browser does change to the location the user wanted to go to.

This is the custom hook I'm using -
export const useWarnIfUnsavedChanges = (unsavedChanges: boolean) => {
  useEffect(() => {
    // For reloading.
    window.onbeforeunload = () => {
      if (unsavedChanges) {
        return "You have unsaved changes. Do you really want to leave?";
      }
    };

    // For changing in-app route.
    if (unsavedChanges) {
      const routeChangeStart = () => {
        const ok = confirm(
          "You have unsaved changes. Do you really want to leave?"
        );
        console.log(ok);
        if (!ok) {
          Router.events.emit("routeChangeError");
          throw new Error("Abort route change. Please ignore this error.");
        }
      };

      Router.events.on("routeChangeStart", routeChangeStart);
      return () => {
        Router.events.off("routeChangeStart", routeChangeStart);
      };
    }
  }, [unsavedChanges]);
};

0 Replies