GWANHUI KIM
GWANHUI KIM

Reputation: 443

How to set the initial screen depending on first launch or not?

I'm using AsyncStorage to detect whether it's first launch or not.

If the users launch the app for the first time, the app takes them to "TourScreen1" page. Or "Feed".

but below code is not working.

this returns object. It should return string.

Is there a way to make this code return string?

Or do I need to use another way?

const Initial = createAppContainer(
  createSwitchNavigator(
    {
      Cover,
      TourScreen1,
      TourScreen2,
      TourScreen3,
      TourScreen4,
      Register: RegisterToLogin,
      Feed: TabNavigator
    },
    {
      initialRouteName: AsyncStorage.getItem("isLaunched").then(value => {
        if (value === null) {
          return "TourScreen1";
        } else return "Feed";
      })
    }
  )
);

Upvotes: 0

Views: 1935

Answers (2)

Suraj Malviya
Suraj Malviya

Reputation: 3783

getItem returns a promise which is an object, createSwitchNavigator is synchronous and doesn't wait for the getItem's promise to be fulfilled or rejected to finish up being executed. So, the promise is being fed to your initialRoute which is an object which is causing the error.

Coming to dynamic initialRoute values, there is no way to dynamically set the initialRoute https://reactnavigation.org/docs/en/limitations.html#dynamic-routes

At least till [email protected] there is no way in any navigators of React Navigation, so to achieve so what you can do is to dynamically create the navigator itself upon your data if you want to stick to the same React Navigation's version or prefer upgrading the navigation lib to React Navigation 5 which overcomes this limitation. Tthe reference link mentioned above for the limitation being quoted in React Navigation's official doc also contains hyperlink for the new API overcoming this limitation.

Hope this helps. Cheers!

Upvotes: 1

Gaurav Roy
Gaurav Roy

Reputation: 12215

Since createSwitchNavigator is synchronous as suraj said, you cant give dynamic initialroute name, What i did is ive made a splashscreen as initial page and that page would just have A logo of your app, and in that page you could have :

    class SplashScreen extends React.Component {
        constructor(){
            super();

        }
        componentDidMount(){
            AsyncStorage.getItem("alreadyLaunched").then(value => {
                if(value == null){
                     AsyncStorage.setItem('alreadyLaunched', true); // No need to wait for `setItem` to finish, although you might want to handle errors
                     this.props.navigation.navigate('FirstTimeScreen');
                }
                else{
                   this.props.navigation.navigate('UsualScreen');
                }}) // Add some error handling, also you can simply do 
        }
        render(){
           return(
<Image /> // image of app
)
    }

hope it helps. feel free for doubts

Upvotes: 1

Related Questions