Last active
May 11, 2023 09:52
-
-
Save denchiklut/3fb99fb0c3396c704bdb8392525d4504 to your computer and use it in GitHub Desktop.
usePromt
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
import { useEffect } from 'react' | |
import { unstable_useBlocker as useBlocker } from 'react-router-dom' | |
export function usePrompt(message: string, when = true) { | |
const blocker = useBlocker(when) | |
useEffect(() => { | |
if (when) window.onbeforeunload = () => message | |
return () => { | |
window.onbeforeunload = null | |
} | |
}, [message, when]) | |
useEffect(() => { | |
if (blocker.state === 'blocked') { | |
if (window.confirm(message)) blocker.proceed() | |
else blocker.reset() | |
} | |
}, [blocker, message]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment