MCPcopy Create free account
hub / github.com/dailydotdev/apps / useExitConfirmation

Function useExitConfirmation

packages/shared/src/hooks/useExitConfirmation.ts:14–80  ·  view source on GitHub ↗
({
  message = 'You have unsaved changes that will be lost if you leave the page',
  onValidateAction,
  enabled = true,
}: ExitProps)

Source from the content-addressed store, hash-verified

12}
13
14export 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 = (url: string, { shallow }: { shallow?: boolean }) => {
44 // Shallow changes on the same page (e.g. ?tab=) leave nothing behind.
45 if (
46 shallow &&
47 new URL(url, window.location.href).pathname === window.location.pathname
48 ) {
49 return;
50 }
51
52 const shouldAskConfirmation = checkShouldAskConfirmation();
53
54 // eslint-disable-next-line no-restricted-globals,no-alert
55 if (shouldAskConfirmation || confirm(message)) {
56 return;
57 }
58
59 router.events.emit('routeChangeError');
60 // Throwing a string (not an Error) is Next.js's documented way to abort a
61 // route change without triggering the dev error overlay.
62 // eslint-disable-next-line @typescript-eslint/no-throw-literal
63 throw 'Route change aborted by useExitConfirmation. Please ignore this error.';
64 };
65
66 window.addEventListener('beforeunload', closeHandler);
67 router.events.on('routeChangeStart', routeHandler);
68
69 return () => {
70 window.removeEventListener('beforeunload', closeHandler);
71 router.events.off('routeChangeStart', routeHandler);

Callers 10

OpportunityEditInfoModalFunction · 0.90
BuyCoresProcessingFunction · 0.90
useFeedSettingsEditFunction · 0.90
useDiscardPostFunction · 0.90

Calls 1

useRouterFunction · 0.50

Tested by

no test coverage detected