how to set initialRouteName dynamically in the react-native

Solution 1:

See according to the docs, initialRoute name should not be a async func .

So ideally what you should do is , anyways you need a splashscreen for your app right, where you display the logo and name of app. Make that page the initialRoute and in its componentDidMount, check for the async function and navigate to ddesired page.

Like what ive done :

createSwitchNavigator(
    {
      App: TabNavigator,
      Auth: AuthStack,
      SplashScreen: SplashScreen,
    },
    {
      initialRouteName: 'SplashScreen',
    },
  ),

And inside SplashScreen im doing :

componentDidMount(){
 if (token) {
      this.props.navigation.navigate('App');
    } else {
      this.props.navigation.navigate('Auth');
    }

}

Hope its clear. Feel free for doubts

Solution 2:

As you can see here:

If you need to set the initialRouteName as a prop it is because there is some data that you need to fetch asynchronously before you render the app navigation. another way to handle this is to use a switchnavigator and have a screen that you show when you are fetching the async data, then navigate to the appropriate initial route with params when necessary. see docs for a full example of this.

Take a look at here.

You'll find more description!

Also quick fix for this situation is check your condition inside SplashScreen componentDidMount() function

Example of SplashScreen :

componentDidMount(){
  AsyncStorage.getItem('unit')
    .then(unit => {
      if(unit){
       this.props.navigation.navigate('Home')
      }else{
       this.props.navigation.navigate('secondTab')
      }
    })
    .catch(err => {

    });
}