Prevent routing to another page except when the form page is submitted

I have a custom context UserRegistrationContextProvider that saves the form data and submit it, and my page is a form that I want to detect before the user change the route to prevent it and show a popup asking to confirm navigation or cancel, I made a custom use hook (useLeavePageConfirm) to handle this logic. The problem I am facing is when the user submit the form, I want to navigate to other page and this trigger the event so the popup appear and I don’t want it to appear nor to prevent the routing in this case.

Is there a way to achieve this flow?

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/router";

const FormContext = createContext<{
  submitNavigation: boolean;
  setSubmitNavigaton: React.Dispatch<SetStateAction<boolean>>;
}>({} as any);

export const useUserRegistrationContext = () => useContext(FormContext);

export const UserRegistrationContextProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {

  const [submitNavigation, setSubmitNavigaton] = useState(false);
  //rest of the code...

  const router = useRouter();
  const userFormMethods = useForm<FormData>({
    mode: "onChange",
    resolver: zodResolver(createValidationSchema()),
  });

  const onUserRegSubmit = userFormMethods.handleSubmit(async (data) => {
    try {
      const regResponse = await axiosInstance.post(/subscribers/",
        { user: data},
        {
          headers: { "Content-Type": "application/json" },
        },
      );
      if (regResponse.status === 201) {
          setSubmitNavigaton(true);
        router.push("/registration/success");
      }
    } catch (error: any) {
      if (error?.response) setErrorObject(error?.response);
    
    }
  });

  return (
    <FormContext.Provider
      value={{
        ....
        onUserRegSubmit,
        submitNavigation,
        setSubmitNavigaton,
      }}
    >
      {children}
    </FormContext.Provider>
  );
};

and in my page where I have the form I made a formLayout like this

const FormsLayout: React.FC<IFormsLayout> = ({
  children,
  pageProps,
  ...divProps
}) => {
  const { onUserRegSubmit, onUserEditSubmit, userFormMethods } =
    useUserRegistrationContext();
  const [sideMenu, setSideMenu] =
    useState<{ name: string; children?: string[] }[]>();
  return (
    <div>
      <div className="hidden xl:block">
        <FormTitle client={pageProps?.client} form={form} />
      </div>
      <div
        {...divProps}
      >
          <SideMenu/>
        <div>
            <FormProvider {...userFormMethods}>
              <form
                id="reg-form"
                onSubmit={
                  pageProps?.client !== null
                    ? onUserEditSubmit
                    : onUserRegSubmit
                }
              >
                {children}
              </form>
            </FormProvider>
        </div>
      </div>
    </div>
  );
};
export const getFormsLayout = (_page: ReactElement, pageProps?: any) => {
  return getPrimaryLayout(
    <UserRegistrationContextProvider>
        <FormsLayout pageProps={pageProps}>{_page}</FormsLayout>
    </UserRegistrationContextProvider>,
    pageProps,
  );
};
export default FormsLayout;

and here is my use custom hook useLeavePageConfirm

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/router";
import { useUserRegistrationContext } from "@/context/userRegistrationContext";

export const useLeavePageConfirm = (
  isDirty: boolean,
  setShowPopup: any,
) => {
  const [nextRouterPath, setNextRouterPath] = useState<string>("");

  const router = useRouter();
  const { submitNavigation } = useUserRegistrationContext();
  const onRouteChangeStart = useCallback(
    (nextPath: string) => {
      if (!isDirty || submitNavigation) {
        return;
      }
      setShowPopup(true);
      setNextRouterPath(nextPath);
      router.events.emit("routeChangeError");
      throw "routeChange aborted.";
    },
    [isDirty, submitNavigation],
  );

  const onRejectRouteChange = () => {
    //setNextRouterPath(null);
    setShowPopup(false);
  };

  const onConfirmRouteChange = () => {
    setShowPopup(false);
    removeListener();
    router.push(nextRouterPath);
  };

  const removeListener = () => {
    router.events.off("routeChangeStart", onRouteChangeStart);
  };

  useEffect(() => {
    router.events.on("routeChangeStart", onRouteChangeStart);

    return removeListener;
  }, [onRouteChangeStart, submitNavigation]);

  return { onConfirmRouteChange, onRejectRouteChange };
};

and here is my page

import React, { useEffect, useState } from "react";
import { useUserRegistrationContext } from "@/context/userRegistrationContext";
import { useLeavePageConfirm } from "@/hooks/useLeavePageConfirm";
import LeavePageConfirmation from "@/components/common/popups/LeavePageConfirm";

const UserRegistration= () => {
  const router = useRouter();
  const [showPopup, setShowPopup] = useState(false);

  const {
    submitNavigation,
    userFormMethods: {
      setValue,
      formState: { isDirty },
    },
  } = useUserRegistrationContext();

  const { onConfirmRouteChange, onRejectRouteChange } = useLeavePageConfirm(
    isDirty,
    setShowPopup,
  );
  let content;
  switch (step) {
    case "step1":
      content = (
        <>
          <UserInfo client={client} />
          <LeavePageConfirmation
            show={showPopup}
            onConfirm={onConfirmRouteChange}
            onCancel={onRejectRouteChange}
            setShowPopup={setShowPopup}
          />
        </>
      );

      break;
    case "step2":
      content = (
        <>
          <PasswordInfo client={client} />
          <LeavePageConfirmation
            show={showPopup}
            onConfirm={onConfirmRouteChange}
            onCancel={onRejectRouteChange}
            setShowPopup={setShowPopup}
          />
        </>
      );
      break;
    
  }
  return <>{content}</>;
};

UserRegistration.getLayout = getFormsLayout;
export default UserRegistration;

I expect to prevent the routing unless the user confirms the popup but also to not prevent when the user submit the form correctly in order to navigate it to another page.

I tried to add a submitNavigation state to indicate when the request is accepted and check it in the useLeavePageConfirm hook but due to the asynchronous state it didn’t work correctly each time.
I also thought to pass a function from the use custom hook to remove the listener and pass to the submit function in the context but couldn’t make it in this structure.

I am using page router nextjs.
Thank you!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật