( enabled: boolean, )
| 15 | * the returned state. |
| 16 | */ |
| 17 | export 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 | }; |
no test coverage detected