Last active
July 11, 2020 05:43
-
-
Save JordanMarr/9bc53ef8e84601c87b2b66a8c9a66d5d to your computer and use it in GitHub Desktop.
useUnload
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
open Feliz | |
open Fable.Core.JsInterop | |
/// Uses the onbeforeunload event from a component via the useEffect hook. | |
/// Returning a value of true will notify the user that they may have unsaved changes. | |
let useUnload (promptOnExit: unit -> bool) = | |
let promptOnExitRef = React.useRef promptOnExit | |
React.useEffect(fun () -> | |
let handler (e: Browser.Types.Event) = | |
let prompt = promptOnExitRef.current() | |
if prompt | |
then e.returnValue <- true | |
else () | |
Browser.Dom.window.onbeforeunload <- handler | |
React.createDisposable(fun () -> | |
Browser.Dom.window.removeEventListener("beforeunload", !!handler) | |
) | |
, [| box promptOnExitRef |]) |
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
let page = React.functionComponent(fun props -> | |
useUnload(fun () -> | |
true // prompt the user that they may have unsaved changes | |
) | |
h1 [] [str "Test Page"] | |
) |
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
let page = React.functionComponent(fun props -> | |
let isChanged, setIsChanged = React.useState(false) | |
useUnload(fun () -> | |
// Function component has already been unmounted, so state is already gone. | |
// Prompt the user to save if "unsaved changes detected" message is visible in the DOM. | |
let unsavedChangesDetectedMsg = Browser.Dom.window.document.querySelector("#UnsavedChanges") | |
unsavedChangesDetectedMsg <> null | |
) | |
h1 [] [str "Test Page"] | |
if isChanged then | |
div [Id "UnsavedChanges"] [str "Changes detected!"] | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment