({
message = 'You have unsaved changes that will be lost if you leave the page',
onValidateAction,
enabled = true,
}: ExitProps)
| 12 | } |
| 13 | |
| 14 | export function useExitConfirmation({ |
| 15 | message = 'You have unsaved changes that will be lost if you leave the page', |
| 16 | onValidateAction, |
| 17 | enabled = true, |
| 18 | }: ExitProps): UseExitConfirmation { |
| 19 | const confirmRef = useRef(true); |
| 20 | const router = useRouter(); |
| 21 | |
| 22 | const checkShouldAskConfirmation = useCallback( |
| 23 | () => !confirmRef.current || onValidateAction(), |
| 24 | [onValidateAction], |
| 25 | ); |
| 26 | |
| 27 | useEffect(() => { |
| 28 | if (!enabled || !router.isReady) { |
| 29 | return undefined; |
| 30 | } |
| 31 | |
| 32 | const closeHandler = (e: BeforeUnloadEvent) => { |
| 33 | const shouldAskConfirmation = checkShouldAskConfirmation(); |
| 34 | |
| 35 | if (shouldAskConfirmation) { |
| 36 | return; |
| 37 | } |
| 38 | |
| 39 | e.preventDefault(); |
| 40 | e.returnValue = message; |
| 41 | }; |
| 42 | |
| 43 | const routeHandler = () => { |
| 44 | const shouldAskConfirmation = checkShouldAskConfirmation(); |
| 45 | |
| 46 | // eslint-disable-next-line no-restricted-globals,no-alert |
| 47 | if (shouldAskConfirmation || confirm(message)) { |
| 48 | return; |
| 49 | } |
| 50 | |
| 51 | router.events.emit('routeChangeError'); |
| 52 | // Throwing a string (not an Error) is Next.js's documented way to abort a |
| 53 | // route change without triggering the dev error overlay. |
| 54 | // eslint-disable-next-line @typescript-eslint/no-throw-literal |
| 55 | throw 'Route change aborted by useExitConfirmation. Please ignore this error.'; |
| 56 | }; |
| 57 | |
| 58 | window.addEventListener('beforeunload', closeHandler); |
| 59 | router.events.on('routeChangeStart', routeHandler); |
| 60 | |
| 61 | return () => { |
| 62 | window.removeEventListener('beforeunload', closeHandler); |
| 63 | router.events.off('routeChangeStart', routeHandler); |
| 64 | }; |
| 65 | }, [checkShouldAskConfirmation, enabled, message, router]); |
| 66 | |
| 67 | return { |
| 68 | onAskConfirmation: (value) => { |
| 69 | confirmRef.current = value; |
| 70 | }, |
| 71 | }; |
no test coverage detected