React-navigation navigate at startup

Viewed 361

I am using react-navigation in my app; I have a Navigator like this:

const RootStack = createStackNavigator();

<RootStack.Navigator>
  <RootStack.Screen name="Main" component={Main} />
  <RootStack.Screen name="B" component={B} />
  <RootStack.Screen name="C" component={C} />
</RootStack.Navigator>

Now when the application starts Main will render; I am fetching some data with a redux action and based on that data it can be that I have to redirect the user to C

so in Main component I am simply doing

useEffect(() => {
  if (shouldRedirect)
    console.log('here')
    navigation.navigate('C')
  }
}, [shouldRedirect])

Well at this point I can see the log in the console but the navigation it's not happening; I guess it's due to the fact that something is not ready yet, because just wrapping the navigate in a timeout like the following, makes it work as expected:

useEffect(() => {
  if (shouldRedirect) {
    setTimeout(() => {
      navigation.navigate('C')
    }, 1)
  }
}, [shouldRedirect])

anyway this looks like an ugly workaround; I'd like to understand how to implement this properly...

1 Answers

You should also add navigation to your dependency array:

useEffect(() => {
  if (shouldRedirect)
    console.log('here')
    navigation.navigate('C')
  }
}, [navigation, shouldRedirect])
Related