3

I'm using the default bottom tab navigation app from the expo example

My appnavigator.js looks like this

export default createAppContainer(createSwitchNavigator({
  // You could add another route here for authentication.
  // Read more at https://reactnavigation.org/docs/en/auth-flow.html
  Main: MainTabNavigator,
}));

I want to check if the user is logged in, by checking the asyncstorage loginname value. In the home.js, if there is no loginname, then I want to redirect to the sigin.js page.

phrogg
  • 888
  • 1
  • 13
  • 28
angry kiwi
  • 10,730
  • 26
  • 115
  • 161
  • https://stackoverflow.com/questions/42876690/react-navigation-with-login-screen can you check this ? – errorau Apr 20 '19 at 04:39
  • Can you explain why you removed the whole code from your question? You just made it too broad. – double-beep Apr 30 '19 at 06:02
  • because it's not necessary, the code was broad itself. And the question is quite simple. Also the answer is universal, it doesn't rely a specific code to understand – angry kiwi Apr 30 '19 at 06:06

2 Answers2

3

I suggest creating a file called initializing.js as a screen, which will be the first entry point in the app and put the logic there.

export default class Initializing extends Component {
  async componentDidMount() {
    try {
      const token = await AsyncStorage.getItem('user_token');
      const skipOnBoarding = true;
      const authenticated = true;
      if (token) await goToHome(skipOnBoarding, authenticated);
      else await goToAuth();

      SplashScreen.hide();
    } catch (err) {
      await goToAuth();
      SplashScreen.hide();
    }
  }
 render() {
    return <View />;
  }
}
Yassir Hartani
  • 157
  • 1
  • 6
3

I worked it out. was very easy.

First do this in the appNavigator.js

import SignIn from '../screens/SignIn'

export default createAppContainer(createSwitchNavigator({
  // You could add another route here for authentication.
  // Read more at https://reactnavigation.org/docs/en/auth-flow.html
  Main: MainTabNavigator,
  SignIn: SignIn // signIn is the login page
}));

Next, at the logic where you check for user logined do something like this.

AsyncStorage.getItem('loginname').then((value) => {
    console.log(value)
    this.props.navigation.navigate('SignIn')
})

the prop this.props.navigation.navigate is automatically avaiable in every stack, you dont need to pass it around to use it

angry kiwi
  • 10,730
  • 26
  • 115
  • 161