1 | ;
|
2 |
|
3 | exports.__esModule = true;
|
4 | exports.default = useMounted;
|
5 |
|
6 | var _react = require("react");
|
7 |
|
8 | /**
|
9 | * Track whether a component is current mounted. Generally less preferable than
|
10 | * properlly canceling effects so they don't run after a component is unmounted,
|
11 | * but helpful in cases where that isn't feasible, such as a `Promise` resolution.
|
12 | *
|
13 | * @returns a function that returns the current isMounted state of the component
|
14 | *
|
15 | * ```ts
|
16 | * const [data, setData] = useState(null)
|
17 | * const isMounted = useMounted()
|
18 | *
|
19 | * useEffect(() => {
|
20 | * fetchdata().then((newData) => {
|
21 | * if (isMounted()) {
|
22 | * setData(newData);
|
23 | * }
|
24 | * })
|
25 | * })
|
26 | * ```
|
27 | */
|
28 | function useMounted() {
|
29 | var mounted = (0, _react.useRef)(true);
|
30 | var isMounted = (0, _react.useRef)(function () {
|
31 | return mounted.current;
|
32 | });
|
33 | (0, _react.useEffect)(function () {
|
34 | mounted.current = true;
|
35 | return function () {
|
36 | mounted.current = false;
|
37 | };
|
38 | }, []);
|
39 | return isMounted.current;
|
40 | } |
\ | No newline at end of file |