fix: support sync getInitialURL in native useLinking

This commit is contained in:
Satyajit Sahoo
2021-01-13 21:54:10 +01:00
parent 47f28558d6
commit b26b90706f
3 changed files with 37 additions and 12 deletions

View File

@@ -67,7 +67,11 @@ export type LinkingOptions = {
* }
* ```
*/
getInitialURL?: () => Promise<string | null | undefined>;
getInitialURL?: () =>
| string
| null
| undefined
| Promise<string | null | undefined>;
/**
* Custom function to get subscribe to URL updates.
* Uses `Linking.addEventListener('url', callback)` by default.

View File

@@ -8,6 +8,8 @@ import {
import escapeStringRegexp from 'escape-string-regexp';
import type { LinkingOptions } from './types';
type ResultState = ReturnType<typeof getStateFromPathDefault>;
let isUsingLinking = false;
export default function useLinking(
@@ -96,19 +98,39 @@ export default function useLinking(
return undefined;
}, []);
const getInitialState = React.useCallback(async () => {
if (!enabledRef.current) {
return undefined;
const getInitialState = React.useCallback(() => {
let state: ResultState | undefined;
if (enabledRef.current) {
const url = getInitialURLRef.current();
if (url != null && typeof url !== 'string') {
return url.then((url) => {
const path = url ? extractPathFromURL(url) : null;
return path
? getStateFromPathRef.current(path, configRef.current)
: undefined;
});
}
const path = url ? extractPathFromURL(url) : null;
state = path
? getStateFromPathRef.current(path, configRef.current)
: undefined;
}
const url = await getInitialURLRef.current();
const path = url ? extractPathFromURL(url) : null;
const thenable = {
then(onfulfilled?: (state: ResultState | undefined) => void) {
return Promise.resolve(onfulfilled ? onfulfilled(state) : state);
},
catch() {
return thenable;
},
};
if (path) {
return getStateFromPathRef.current(path, configRef.current);
} else {
return undefined;
}
return thenable as PromiseLike<ResultState | undefined>;
}, [extractPathFromURL]);
React.useEffect(() => {

View File

@@ -352,7 +352,6 @@ export default function useLinking(
}
}
// Make it a thenable to keep consistent with the native impl
const thenable = {
then(onfulfilled?: (state: ResultState | undefined) => void) {
return Promise.resolve(onfulfilled ? onfulfilled(value) : value);