Passed
Push — feature/connect-application-st... ( a6f23b...9d3dc6 )
by Chris
04:02
created

resources/assets/js/components/Form/AlertWhenUnsaved.tsx   A

Complexity

Total Complexity 1
Complexity/F 0

Size

Lines of Code 29
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 1
eloc 19
mnd 1
bc 1
fnc 0
dl 0
loc 29
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
rs 10
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