plane/web/hooks/use-reload-confirmation.tsx
rahulramesha 95580d0c62
[WEB-881] fix: Sentry errors from previous build (#4142)
* Sentry Fix for "Non-Error promise rejection captured with value: Route change to url was aborted"

* Sentry fix for "undefined is not an object (evaluating 'n.response')"

* Possible Sentry Fix for "TypeError Function.entries(<anonymous>)"

* Possible Sentry fix for "null is not an object (evaluating 'e.type')"
2024-04-09 13:12:14 +05:30

43 lines
1.3 KiB
TypeScript

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/router";
//TODO: remove temp flag isActive later and use showAlert as the source of truth
const useReloadConfirmations = (isActive = true) => {
const [showAlert, setShowAlert] = useState(false);
const router = useRouter();
const handleBeforeUnload = useCallback(
(event: BeforeUnloadEvent) => {
if (!isActive || !showAlert) return;
event.preventDefault();
event.returnValue = "";
},
[isActive, showAlert]
);
const handleRouteChangeStart = useCallback(
(url: string) => {
if (!isActive || !showAlert) return;
const leave = confirm("Are you sure you want to leave? Changes you made may not be saved.");
if (!leave) {
router.events.emit("routeChangeError");
}
},
[isActive, showAlert, router.events]
);
useEffect(() => {
window.addEventListener("beforeunload", handleBeforeUnload);
router.events.on("routeChangeStart", handleRouteChangeStart);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
router.events.off("routeChangeStart", handleRouteChangeStart);
};
}, [handleBeforeUnload, handleRouteChangeStart, router.events]);
return { setShowAlert };
};
export default useReloadConfirmations;