Skip to content

Instantly share code, notes, and snippets.

@JordanMarr
Last active July 11, 2020 05:43
Show Gist options
  • Save JordanMarr/9bc53ef8e84601c87b2b66a8c9a66d5d to your computer and use it in GitHub Desktop.
Save JordanMarr/9bc53ef8e84601c87b2b66a8c9a66d5d to your computer and use it in GitHub Desktop.
useUnload
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 |])
let page = React.functionComponent(fun props ->
useUnload(fun () ->
true // prompt the user that they may have unsaved changes
)
h1 [] [str "Test Page"]
)
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