UNPKG

5.42 kBJavaScriptView Raw
1import * as React from 'react';
2import { Linking, Platform } from 'react-native';
3import { getActionFromState as getActionFromStateDefault, getStateFromPath as getStateFromPathDefault } from '@react-navigation/core';
4import extractPathFromURL from './extractPathFromURL';
5let isUsingLinking = false;
6export default function useLinking(ref, {
7 enabled = true,
8 prefixes,
9 config,
10 getInitialURL = () => Promise.race([Linking.getInitialURL(), new Promise(resolve => // Timeout in 150ms if `getInitialState` doesn't resolve
11 // Workaround for https://github.com/facebook/react-native/issues/25675
12 setTimeout(resolve, 150))]),
13 subscribe = listener => {
14 const callback = ({
15 url
16 }) => listener(url);
17
18 const subscription = Linking.addEventListener('url', callback);
19 return () => {
20 // https://github.com/facebook/react-native/commit/6d1aca806cee86ad76de771ed3a1cc62982ebcd7
21 if (subscription !== null && subscription !== void 0 && subscription.remove) {
22 subscription.remove();
23 } else {
24 Linking.removeEventListener('url', callback);
25 }
26 };
27 },
28 getStateFromPath = getStateFromPathDefault,
29 getActionFromState = getActionFromStateDefault
30}) {
31 React.useEffect(() => {
32 if (enabled !== false && isUsingLinking) {
33 throw new Error(['Looks like you have configured linking in multiple places. This is likely an error since deep links should only be handled in one place to avoid conflicts. Make sure that:', "- You are not using both 'linking' prop and 'useLinking'", "- You don't have 'useLinking' in multiple components", Platform.OS === 'android' ? "- You have set 'android:launchMode=singleTask' in the '<activity />' section of the 'AndroidManifest.xml' file to avoid launching multiple instances" : ''].join('\n').trim());
34 } else {
35 isUsingLinking = enabled !== false;
36 }
37
38 return () => {
39 isUsingLinking = false;
40 };
41 }); // We store these options in ref to avoid re-creating getInitialState and re-subscribing listeners
42 // This lets user avoid wrapping the items in `React.useCallback` or `React.useMemo`
43 // Not re-creating `getInitialState` is important coz it makes it easier for the user to use in an effect
44
45 const enabledRef = React.useRef(enabled);
46 const prefixesRef = React.useRef(prefixes);
47 const configRef = React.useRef(config);
48 const getInitialURLRef = React.useRef(getInitialURL);
49 const getStateFromPathRef = React.useRef(getStateFromPath);
50 const getActionFromStateRef = React.useRef(getActionFromState);
51 React.useEffect(() => {
52 enabledRef.current = enabled;
53 prefixesRef.current = prefixes;
54 configRef.current = config;
55 getInitialURLRef.current = getInitialURL;
56 getStateFromPathRef.current = getStateFromPath;
57 getActionFromStateRef.current = getActionFromState;
58 });
59 const getInitialState = React.useCallback(() => {
60 let state;
61
62 if (enabledRef.current) {
63 const url = getInitialURLRef.current();
64
65 if (url != null && typeof url !== 'string') {
66 return url.then(url => {
67 const path = url ? extractPathFromURL(prefixesRef.current, url) : null;
68 return path ? getStateFromPathRef.current(path, configRef.current) : undefined;
69 });
70 }
71
72 const path = url ? extractPathFromURL(prefixesRef.current, url) : null;
73 state = path ? getStateFromPathRef.current(path, configRef.current) : undefined;
74 }
75
76 const thenable = {
77 then(onfulfilled) {
78 return Promise.resolve(onfulfilled ? onfulfilled(state) : state);
79 },
80
81 catch() {
82 return thenable;
83 }
84
85 };
86 return thenable;
87 }, []);
88 React.useEffect(() => {
89 const listener = url => {
90 if (!enabled) {
91 return;
92 }
93
94 const path = extractPathFromURL(prefixesRef.current, url);
95 const navigation = ref.current;
96
97 if (navigation && path) {
98 const state = getStateFromPathRef.current(path, configRef.current);
99
100 if (state) {
101 // Make sure that the routes in the state exist in the root navigator
102 // Otherwise there's an error in the linking configuration
103 const rootState = navigation.getRootState();
104
105 if (state.routes.some(r => !(rootState !== null && rootState !== void 0 && rootState.routeNames.includes(r.name)))) {
106 console.warn("The navigation state parsed from the URL contains routes not present in the root navigator. This usually means that the linking configuration doesn't match the navigation structure. See https://reactnavigation.org/docs/configuring-links for more details on how to specify a linking configuration.");
107 return;
108 }
109
110 const action = getActionFromStateRef.current(state, configRef.current);
111
112 if (action !== undefined) {
113 try {
114 navigation.dispatch(action);
115 } catch (e) {
116 // Ignore any errors from deep linking.
117 // This could happen in case of malformed links, navigation object not being initialized etc.
118 console.warn("An error occurred when trying to handle the link '".concat(path, "': ").concat(e.message));
119 }
120 } else {
121 navigation.resetRoot(state);
122 }
123 }
124 }
125 };
126
127 return subscribe(listener);
128 }, [enabled, ref, subscribe]);
129 return {
130 getInitialState
131 };
132}
133//# sourceMappingURL=useLinking.native.js.map
\No newline at end of file