Skip to content

Commit

Permalink
alert before leaving unsaved modifications
Browse files Browse the repository at this point in the history
  • Loading branch information
hughcrt committed Dec 10, 2024
1 parent 40c2c81 commit 14efa26
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions packages/frontend/pages/dashboards/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,34 @@ export default function Dashboard() {
};
return JSON.stringify(current) !== JSON.stringify(initial);
}, [dashboard, checks, startDate, endDate, granularity, charts]);
useEffect(() => {
const beforeUnload = (e: BeforeUnloadEvent) => {
if (isDirty) {
e.preventDefault();
return "";
}
};

const handleRouteChange = (url: string) => {
if (
isDirty &&
!confirm("You have unsaved changes. Do you really want to leave?")
) {
router.events.emit("routeChangeError");
throw "Route change aborted by user";
}
};

if (isDirty) {
window.addEventListener("beforeunload", beforeUnload);
router.events.on("routeChangeStart", handleRouteChange);
}

return () => {
window.removeEventListener("beforeunload", beforeUnload);
router.events.off("routeChangeStart", handleRouteChange);
};
}, [isDirty, router.events]);

if (dashboardIsLoading || !dashboard) {
return (
Expand Down

0 comments on commit 14efa26

Please sign in to comment.