1 | import { nanoid } from 'nanoid/non-secure';
|
2 | import * as React from 'react';
|
3 | import useLatestCallback from 'use-latest-callback';
|
4 | import useNavigation from './useNavigation';
|
5 | import usePreventRemoveContext from './usePreventRemoveContext';
|
6 | import useRoute from './useRoute';
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | export default function usePreventRemove(preventRemove, callback) {
|
15 | const [id] = React.useState(() => nanoid());
|
16 | const navigation = useNavigation();
|
17 | const {
|
18 | key: routeKey
|
19 | } = useRoute();
|
20 | const {
|
21 | setPreventRemove
|
22 | } = usePreventRemoveContext();
|
23 | React.useEffect(() => {
|
24 | setPreventRemove(id, routeKey, preventRemove);
|
25 | return () => {
|
26 | setPreventRemove(id, routeKey, false);
|
27 | };
|
28 | }, [setPreventRemove, id, routeKey, preventRemove]);
|
29 | const beforeRemoveListener = useLatestCallback(e => {
|
30 | if (!preventRemove) {
|
31 | return;
|
32 | }
|
33 |
|
34 | e.preventDefault();
|
35 | callback({
|
36 | data: e.data
|
37 | });
|
38 | });
|
39 | React.useEffect(() => navigation === null || navigation === void 0 ? void 0 : navigation.addListener('beforeRemove', beforeRemoveListener), [navigation, beforeRemoveListener]);
|
40 | }
|
41 |
|
\ | No newline at end of file |