File size: 949 Bytes
4114d85 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import { useCallback, useContext, useEffect } from 'react'
import { UNSAFE_NavigationContext as NavigationContext } from 'react-router-dom'
// https://stackoverflow.com/questions/71572678/react-router-v-6-useprompt-typescript
export function useBlocker(blocker, when = true) {
const { navigator } = useContext(NavigationContext)
useEffect(() => {
if (!when) return
const unblock = navigator.block((tx) => {
const autoUnblockingTx = {
...tx,
retry() {
unblock()
tx.retry()
}
}
blocker(autoUnblockingTx)
})
return unblock
}, [navigator, blocker, when])
}
export function usePrompt(message, when = true) {
const blocker = useCallback(
(tx) => {
if (window.confirm(message)) tx.retry()
},
[message]
)
useBlocker(blocker, when)
}
|