-
Notifications
You must be signed in to change notification settings - Fork 532
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added logic for preventing navigation on dirty form
- Loading branch information
1 parent
adac786
commit 22da20d
Showing
2 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import { useEffect } from "react"; | ||
|
||
interface UsePreventNavigationOptions { | ||
isDirty: boolean; | ||
message?: string; | ||
} | ||
|
||
export function usePreventNavigation({ | ||
isDirty, | ||
message = "You have unsaved changes. Are you sure you want to leave?", | ||
}: UsePreventNavigationOptions) { | ||
useEffect(() => { | ||
if (!isDirty) return; | ||
|
||
const handleBeforeUnload = (e: BeforeUnloadEvent) => { | ||
e.preventDefault(); | ||
e.returnValue = ""; | ||
return ""; | ||
}; | ||
|
||
const preventNavigation = (e: Event) => { | ||
const confirmLeave = window.confirm(message); | ||
|
||
if (!confirmLeave) { | ||
e.preventDefault(); | ||
e.stopPropagation(); | ||
window.history.replaceState(null, "", window.location.pathname); | ||
return false; | ||
} | ||
}; | ||
|
||
const handleLinkClick = (e: MouseEvent) => { | ||
const link = (e.target as HTMLElement).closest("a"); | ||
if (link) preventNavigation(e); | ||
}; | ||
|
||
// Common options for event listeners | ||
const listenerOptions = { capture: true }; | ||
|
||
window.addEventListener("beforeunload", handleBeforeUnload); | ||
window.addEventListener("popstate", preventNavigation, listenerOptions); | ||
document.addEventListener("click", handleLinkClick, listenerOptions); | ||
|
||
return () => { | ||
window.removeEventListener("beforeunload", handleBeforeUnload); | ||
window.removeEventListener( | ||
"popstate", | ||
preventNavigation, | ||
listenerOptions, | ||
); | ||
document.removeEventListener("click", handleLinkClick, listenerOptions); | ||
}; | ||
}, [isDirty, message]); | ||
} |