1
0
mirror of https://github.com/sasjs/server.git synced 2026-01-09 23:40:06 +00:00

feat: prevent user from leaving studio page when there are unsaved changes

This commit is contained in:
2022-07-25 22:41:05 +05:00
parent 2360e104bd
commit 6c7550286b
3 changed files with 44 additions and 1 deletions

View File

@@ -0,0 +1,36 @@
import { useEffect, useCallback, useContext } from 'react'
import { UNSAFE_NavigationContext as NavigationContext } from 'react-router-dom'
import { History, Blocker, Transition } from 'history'
function useBlocker(blocker: Blocker, when = true) {
const navigator = useContext(NavigationContext).navigator as History
useEffect(() => {
if (!when) return
const unblock = navigator.block((tx: Transition) => {
const autoUnblockingTx = {
...tx,
retry() {
unblock()
tx.retry()
}
}
blocker(autoUnblockingTx)
})
return unblock
}, [navigator, blocker, when])
}
export default function usePrompt(message: string, when = true) {
const blocker = useCallback(
(tx) => {
if (window.confirm(message)) tx.retry()
},
[message]
)
useBlocker(blocker, when)
}