Skip to content

Instantly share code, notes, and snippets.

@tzynwang
Last active February 17, 2022 12:08
import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'
import { UnregisterCallback } from 'history'
interface useBlockArgs {
block?: boolean
}
let BLOCK: UnregisterCallback
export default function useBlock(args: useBlockArgs) {
const history = useHistory()
const { block } = args
const preventCloseAndRefresh = (event: BeforeUnloadEvent) => {
const e = event || window.event
e.preventDefault()
if (e) e.returnValue = ''
return ''
}
useEffect(() => {
if (block === false) return
window.addEventListener('beforeunload', preventCloseAndRefresh)
BLOCK = history.block(() => {
const leave = window.confirm('Leave this page?')
if (!leave) {
return false
}
return undefined
})
return () => {
window.removeEventListener('beforeunload', preventCloseAndRefresh)
BLOCK()
}
}, [block])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment