I have a react native app, on the Home Screen I have the code to open the deep link. I check if the deep link exists using Linking.getInitialURL()
and then I redirect the user if the initialUrl exists, this flow works fine but the deep link doesn’t get cleared.
For example,if I click on the deep link
myapp://home/gallery it takes me to a Gallery screen. When I click on Go Home button on the Gallery screen, I go to the Home Screen. But Linking.getInitialURL()
detects the myapp://home/gallery link agan and redirects the user back to the Gallery screen. Only after this, if I go to the Home screen the initialUtl is null. How can I clear the Linking.getInitialURL()
after the link has been opened already the first time, why the react-native doesn’t detect it?
I tried to check Linking.getInitialURL()
every time screen focuses( by refreshing the screen) but still
Linking.getInitialURL()
is returning the deep link first time the user goes to home from gallery.
Any help and advise is appreciated.
Edit (added code)
// Home screen
useEffect(()=> {
const getLink = async () => {
const link = Linking.getInitialURL()
if (link){
await Linking.openURL(url)}
}
getLink()
},[])
2
Answers
you are using useEffect() and as you configured it it probably fires when you load the Home screen – please verify the same with some logs.
In general I would not specify the function within the useEffect block and use a const with
useState()
to store the state for link. Then you can put the same in the[linkState]
brackets in useEffect, thus useEffect will only fire when the linkState has changed.Additionally you are working here with deep links, then I would rather have the code for the same in the navigation
index.js
. That will allow you to avoid any side effects like you are facing.Perhaps in your case you can store the link in central state (like redux) and compare the link which is about to be opened with the one in central state.
Also, I think RN recommends checking a link with canOpenURL before opening it.
Something like this