Show login screen if user is not logged in when opening the app with react-navigation

Viewed 3505

I am trying to create an app which has a main tab navigator, but if the user is not logged in, he/she should first see a login screen (however, I still want the user to get the option to skip login).

Also, if it's the first time the user opens the app, I want to show an onboarding/welcome screen where I explain the app.

Right now I am persisting my redux state with redux-persist, so when I open the app (i.e. without having it opened in the background), I want the user to see the Login screen if he/she is not logged in and the Main screen if the user is already logged in.

I have understood that I should have my main tab navigator nested in a stack navigator, such that the stack navigator has screens WelcomeScreen, LoginScreen and Main.

But how do I check if the user is logged in when the app is first opened and then redirect to the Login screen? I have looked at https://github.com/react-community/react-navigation/blob/master/examples/ReduxExample/src/reducers/index.js, but it's not very intuitive what is meant by firstAction, tempNavState, and secondAction.

Do I need to create a middleware which checks if the user is logged in?

1 Answers

In the root container check for login state if the user is loggedin or not and navigate accordingly. See this post Login example don't use async storage as he used in the post instead use redux state to determine user is logged in. Another trick which is user friendly is to use react-native-splash-screen and don't hide the splash screen using this package, wait for 2 seconds, so that redux-persist action is dispatched which restores the state and you can navigate during this time period. There will be no flickering using this method.

class AppWithNavigationState extends Component { 
    componentDidMount () { 
       setTimeout(()=>{ 
             if(this.props.loggedIn)
               { NavigationActions.navigate({ routeName: 'Main' }), } 

               setTimeout(SplashScreen.hide, 500)
     })
   }}
Related