feat: add confirm dialog for leaving the page if an upload is in progress
This commit is contained in:
42
frontend/src/hooks/confirm-leave.hook.ts
Normal file
42
frontend/src/hooks/confirm-leave.hook.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect } from "react";
|
||||
|
||||
const useConfirmLeave = ({
|
||||
message,
|
||||
enabled,
|
||||
}: {
|
||||
message: string;
|
||||
enabled: boolean;
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
|
||||
// Show confirmation dialog when route changes
|
||||
const handleRouteChange = () => {
|
||||
const confirmLeave = window.confirm(message);
|
||||
if (!confirmLeave) {
|
||||
router.events.emit("routeChangeError");
|
||||
throw "Route change aborted.";
|
||||
}
|
||||
};
|
||||
|
||||
// Show confirmation when the user tries to leave or reload the page
|
||||
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault();
|
||||
event.returnValue = message;
|
||||
return message;
|
||||
};
|
||||
|
||||
router.events.on("routeChangeStart", handleRouteChange);
|
||||
window.addEventListener("beforeunload", handleBeforeUnload);
|
||||
|
||||
return () => {
|
||||
router.events.off("routeChangeStart", handleRouteChange);
|
||||
window.removeEventListener("beforeunload", handleBeforeUnload);
|
||||
};
|
||||
}, [router, message, enabled]);
|
||||
};
|
||||
|
||||
export default useConfirmLeave;
|
||||
Reference in New Issue
Block a user