Total Complexity | 1 |
Complexity/F | 0 |
Lines of Code | 29 |
Function Count | 0 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | import React, { useEffect } from "react"; |
||
2 | import { useFormikContext } from "formik"; |
||
3 | |||
4 | // Kinda weird "empty" component that hooks into Formik's |
||
5 | // context, listens to the 'dirty' prop, and registers |
||
6 | // a beforeunload listener to fire if a user attempts to |
||
7 | // leave with unsaved work. |
||
8 | // https://github.com/jaredpalmer/formik/issues/1657#issuecomment-509388871 |
||
9 | const AlertWhenUnsaved = (): React.ReactElement => { |
||
10 | const { dirty } = useFormikContext(); |
||
11 | const handleUnload = (event: BeforeUnloadEvent): void => { |
||
12 | event.preventDefault(); |
||
13 | event.returnValue = "Are you sure you want to leave with unsaved changes?"; |
||
14 | }; |
||
15 | |||
16 | useEffect(() => { |
||
17 | if (dirty) { |
||
18 | window.addEventListener("beforeunload", handleUnload); |
||
19 | } |
||
20 | return (): void => { |
||
21 | window.removeEventListener("beforeunload", handleUnload); |
||
22 | }; |
||
23 | }, [dirty]); |
||
24 | |||
25 | return <></>; |
||
26 | }; |
||
27 | |||
28 | export default AlertWhenUnsaved; |
||
29 |