UNPKG

1.43 kBJavaScriptView Raw
1import { nanoid } from 'nanoid/non-secure';
2import * as React from 'react';
3import useLatestCallback from 'use-latest-callback';
4import useNavigation from './useNavigation';
5import usePreventRemoveContext from './usePreventRemoveContext';
6import useRoute from './useRoute';
7/**
8 * Hook to prevent screen from being removed. Can be used to prevent users from leaving the screen.
9 *
10 * @param preventRemove Boolean indicating whether to prevent screen from being removed.
11 * @param callback Function which is executed when screen was prevented from being removed.
12 */
13
14export 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//# sourceMappingURL=usePreventRemove.js.map
\No newline at end of file