Skip to content

Instantly share code, notes, and snippets.

@denchiklut
Last active May 11, 2023 09:52
Show Gist options
  • Save denchiklut/3fb99fb0c3396c704bdb8392525d4504 to your computer and use it in GitHub Desktop.
Save denchiklut/3fb99fb0c3396c704bdb8392525d4504 to your computer and use it in GitHub Desktop.
usePromt
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