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!