Skip to content

Commit

Permalink
fix: support sync getInitialURL in native useLinking
Browse files Browse the repository at this point in the history
  • Loading branch information
satya164 committed Jan 13, 2021
1 parent 47f2855 commit b26b907
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 12 deletions.
6 changes: 5 additions & 1 deletion packages/native/src/types.tsx
Expand Up @@ -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.
Expand Down
42 changes: 32 additions & 10 deletions packages/native/src/useLinking.native.tsx
Expand Up @@ -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(
Expand Down Expand Up @@ -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;

const url = await getInitialURLRef.current();
const path = url ? extractPathFromURL(url) : null;
if (enabledRef.current) {
const url = getInitialURLRef.current();

if (path) {
return getStateFromPathRef.current(path, configRef.current);
} else {
return undefined;
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 thenable = {
then(onfulfilled?: (state: ResultState | undefined) => void) {
return Promise.resolve(onfulfilled ? onfulfilled(state) : state);
},
catch() {
return thenable;
},
};

return thenable as PromiseLike<ResultState | undefined>;
}, [extractPathFromURL]);

React.useEffect(() => {
Expand Down
1 change: 0 additions & 1 deletion packages/native/src/useLinking.tsx
Expand Up @@ -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);
Expand Down

0 comments on commit b26b907

Please sign in to comment.