Mohammad Mas
Mohammad Mas

Reputation: 111

React-native linking getinitialurl() works even when I don't call from external link

I use linking for opening my app from the browser.

When I tap the link for first in-browser my app run but incoming URL don't clear after that and linking.GetInitialUrl() always run with that URL.

My schema is myapp://host and my URL on the web is myapp://host/ok

I click on my URL and linking.getInitialUrl() works but when next time I'm back to My screen linking.getInitialUrl() return my web URL without open web page by me.

componentDidMount() {           
        Linking.getInitialURL().then(url => {            
           if (url) {
              alert(url)
           }
         })
         .catch(err => {
           console.error(err);
         });
           Linking.addEventListener('url',this.handleOpenURL);
    }
    
    
     componentWillUnmount() {           Linking.removeEventListener('url',this.handleOpenURL);
    }
    
    handleOpenURL = (event) => { // D
        this.linkFunc(event.url);
      }

Upvotes: 6

Views: 12292

Answers (1)

FranXho
FranXho

Reputation: 765

Since you are calling getInitialURL method in componentDidMount method without checking if the app is already loaded or not. Your alert(url) will get triggered whenever that component is loaded again.

To solve the problem, you have to call getInitialURL in the root component that will never be loaded again after the app is loaded.Or you can use a global variable to mark the status of your app whether it is already loaded or not.

if(!InMemoryData.appLoaded){
    Linking.getInitialURL().then(url => {
    this._navigate(url);
    InMemoryData.appLoaded = true;
    });  
}

Upvotes: 10

Related Questions