-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Display confirmation dialog if user has unsaved changes
- Loading branch information
1 parent
129f479
commit 357d6bf
Showing
5 changed files
with
67 additions
and
14 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
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
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,30 @@ | ||
import { useEffect } from "react"; | ||
|
||
interface UseDirtyFormProps { | ||
isDirty: boolean; | ||
} | ||
|
||
/** | ||
* A hook that conditionally marks the page as dirty so the browser will display | ||
* a confirmation dialog when the user tries to leave or reload it. | ||
*/ | ||
export const useDirtyForm = ({ isDirty }: UseDirtyFormProps) => { | ||
/** | ||
* Returning true from this event handler tells the browser to display a confirmation | ||
* dialog telling the user they have unsaved changes. | ||
*/ | ||
const handleBeforeUnload = (e: BeforeUnloadEvent) => { | ||
if (!isDirty) { | ||
return false; | ||
} | ||
|
||
e.preventDefault(); | ||
e.returnValue = true; | ||
return true; | ||
}; | ||
|
||
useEffect(() => { | ||
window.addEventListener("beforeunload", handleBeforeUnload); | ||
return () => window.removeEventListener("beforeunload", handleBeforeUnload); | ||
}, [isDirty]); | ||
}; |