MCPcopy Index your code
hub / github.com/coder/coder / useUnsavedChangesPrompt

Function useUnsavedChangesPrompt

site/src/hooks/useUnsavedChangesPrompt.ts:17–43  ·  view source on GitHub ↗
(
	enabled: boolean,
)

Source from the content-addressed store, hash-verified

15 * the returned state.
16 */
17export const useUnsavedChangesPrompt = (
18 enabled: boolean,
19): UnsavedChangesPromptState => {
20 useEffect(() => {
21 if (!enabled) return;
22 const onBeforeUnload = (event: BeforeUnloadEvent) => {
23 event.preventDefault();
24 // Older browsers also require a return value to trigger the prompt.
25 return "";
26 };
27 window.addEventListener("beforeunload", onBeforeUnload);
28 return () => {
29 window.removeEventListener("beforeunload", onBeforeUnload);
30 };
31 }, [enabled]);
32
33 const blocker = useBlocker(
34 ({ currentLocation, nextLocation }) =>
35 enabled && currentLocation.pathname !== nextLocation.pathname,
36 );
37
38 return {
39 isOpen: blocker.state === "blocked",
40 onCancel: () => blocker.reset?.(),
41 onConfirm: () => blocker.proceed?.(),
42 };
43};

Callers 1

ProviderFormFunction · 0.90

Calls 3

addEventListenerMethod · 0.65
removeEventListenerMethod · 0.45
resetMethod · 0.45

Tested by

no test coverage detected