Last active
October 19, 2023 16:36
-
-
Save n8jadams/1ddd86274bf0786d5c0eae0ca36f701d to your computer and use it in GitHub Desktop.
useBeforeClosingWindowPrompt - a hook that prompts user before they close the window when there are unsaved changes
This file contains hidden or 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
import { useEffect } from "react"; | |
/** | |
* A hook that prevents closing or refreshing if there are unsaved changes, | |
* offering the user a prompt to confirm before closing the window. | |
* @param promptBeforeClosingWindow A boolean indicating if we should prompt before closing | |
*/ | |
export function useBeforeClosingWindowPrompt(promptBeforeClosingWindow: boolean) { | |
useEffect((): (() => void) => { | |
function handleBeforeUnload(e: BeforeUnloadEvent): void { | |
e.preventDefault(); | |
// eslint-disable-next-line no-param-reassign | |
e.returnValue = ""; // Chrome requires returnValue to be set | |
} | |
if (promptBeforeClosingWindow) { | |
window.addEventListener("beforeunload", handleBeforeUnload); | |
} | |
return (): void => { | |
if (promptBeforeClosingWindow) { | |
window.removeEventListener("beforeunload", handleBeforeUnload); | |
} | |
}; | |
}, [promptBeforeClosingWindow]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment