-
Notifications
You must be signed in to change notification settings - Fork 39
/
useCallbackPrompt.ts
54 lines (46 loc) · 1.71 KB
/
useCallbackPrompt.ts
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* eslint-disable react-hooks/exhaustive-deps */
import { useCallback, useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router'
import { useBlocker } from './useBlocker'
export function useCallbackPrompt(when: boolean): (boolean | (() => void))[] {
const navigate = useNavigate()
const location = useLocation()
const [showPrompt, setShowPrompt] = useState(false)
const [lastLocation, setLastLocation] = useState<any>(null)
const [confirmedNavigation, setConfirmedNavigation] = useState(false)
const cancelNavigation = useCallback(() => {
setShowPrompt(false)
setLastLocation(null)
}, [])
// handle blocking when user click on another route prompt will be shown
const handleBlockedNavigation = useCallback(
(nextLocation) => {
// in if condition we are checking next location and current location are equals or not
if (
!confirmedNavigation &&
nextLocation.location.pathname !== location.pathname
) {
setShowPrompt(true)
setLastLocation(nextLocation)
return false
}
return true
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[confirmedNavigation, location]
)
const confirmNavigation = useCallback(() => {
setShowPrompt(false)
setConfirmedNavigation(true)
}, [])
useEffect(() => {
if (confirmedNavigation && lastLocation) {
navigate(lastLocation.location?.pathname)
// Clean-up state on confirmed navigation
setConfirmedNavigation(false)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [confirmedNavigation, lastLocation])
useBlocker(handleBlockedNavigation, when)
return [showPrompt, confirmNavigation, cancelNavigation]
}