useURL hook expo-linking for background app

1.5k Views Asked by At

The expo-linking React Native package has a hook named useURL that isn't working for me when the app is in the background. From the docs it Returns the initial URL followed by any subsequent changes to the URL. The problem I'm having with my managed expo app is that the hook doesn't work when the app is already open in the background. Here is the hook:

export default function App() {
  const isLoadingComplete = useCachedResources();
  const url = Linking.useURL();

  useEffect(() => {
    Alert.alert(url ? url.substring(20) : 'null');
  }, [url]);

  if (!isLoadingComplete) {
    return null;
  } else {
    return (
      ...
    );
  }
}

If I open the URL exp://exp.host/@myprofile/myproject?a=bwhen the app is closed, I get an Alert as expected. If the app is in the background, the Alert doesn't go off. I've tested on an iOS emulator and a physical Android. Any solutions? Note that similar problems happen with Linking.addEventListener().

1

There are 1 best solutions below

0
On

you can use:

import { AppState } from 'react-native';

AppState is a module provided by React Native that allows you to access and subscribe to changes in the application's lifecycle state. The application can be in various states, such as 'active' when it's in the foreground, 'background' when it's running in the background, or 'inactive' during transitions between states.

const hasEventListener = useRef(false);
useEffect(() => {
 if (!hasEventListener.current) {
      const subscription = AppState.addEventListener('change', nextAppState => {
        if (nextAppState === 'active') {
    Alert.alert(url ? url.substring(20) : 'null');
}
 });
 return () => {
        subscription.remove();
        hasEventListener.current = false;
      };
    }
  }, [url]);

The hasEventListener variable is being used to ensure that the event listener for the AppState change is only added once.