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

Function useExitConfirmation

packages/shared/src/hooks/useExitConfirmation.ts:14–72  ·  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 = () => {
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 };

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