Home > Software engineering >  Hot to wait for Linking to finish in React Native?
Hot to wait for Linking to finish in React Native?

Time:05-03

I am creating a function that uses the React Native Linking library with the built-in URL scheme for opening the phone app. My idea is to wait until the user either makes the call or clicks on cancel, and then navigate somewhere else.

Here's the code:

const openPhoneCall = async () => {
    await Linking.openURL(`tel:${phoneNum}`);
    navigateToDashboard();
};

My issue is that the phone modal opens and immediately navigates to the dashboard, instead of waiting on either making the call or clicking on cancel and then navigating.

Any way to solve this?

Thank you

CodePudding user response:

I think you can use an app state listener on this screen particularly and call navigateToDashboard whenever the user got a blur event

example:

import React, {useEffect} from 'react';
import {AppState} from 'react-native';
...

function App() {
  ...
  useEffect(() => {
    const listener = AppState.addEventListener('blur', state => {
      navigateToDashboard();
    });

    return listener.remove;
  }, []);
  ...
}

export default App;

CodePudding user response:

I managed to find a way to solve this by using AppState.

const appState = useRef(AppState.currentState);
useEffect(() => {
    const subscription = AppState.addEventListener("change", (nextAppState) => {
      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === "active"
      ) {
        navigateToDashboard();
      }
      appState.current = nextAppState;
    });

    return () => {
      subscription.remove();
    };
 }, []);
  • Related