Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set dynamic 'initialRouteName' in react-native

question is simple I know there are lots of answers available for the same question but I have differently set my own App.js file i tried almost all but no success.

so my App.js looks like this

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  StatusBar
} from 'react-native';
import { createStackNavigator  } from 'react-navigation';
import { Header, Button, Spinner } from './src/components/comman';
import SplashScreen from 'react-native-splash-screen';
import LoginForm from './src/components/LoginForm';
import SignupForm from './src/components/SignupForm';
import Home from './src/components/Home';
import ForgetPassword from './src/components/ForgetPassword';


import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);
const App = createStackNavigator ({
  Login: { screen: LoginForm },
  Home: { screen: Home },
  Signup: { screen: SignupForm },
  ForgetPassword: { screen : ForgetPassword },
  },
  { 
  initialRouteName: 'Login',
  });

export default App;

Now I store login state in AsyncStorage in my LoginForm.js like this

.
.
AsyncStorage.setItem('isLoggedIn', 'true').then((a) => {
    this.onLoginSuccess(responseData.user_id);
});
.
.

so now i want to set initialRouteName based on my local storage element. Simple if isLoggedIn is true then initialRouteName : Home otherwise initialRouteName : Login

Simple but don't how to use this in my App.js

Please help :)

like image 342
Kishan Oza Avatar asked Jun 15 '18 05:06

Kishan Oza


2 Answers

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.

And this is an open RFC

UPDATE

Take a look at here.

You'll find more description!

like image 158
MohamadKh75 Avatar answered Oct 10 '22 15:10

MohamadKh75


You can write like this

 <Stack.Navigator
  {...{initialRouteName: isLoggedIn ? 'Home' : 'Login'}}>
  <Stack.Screen name="Login" component={LoginScreen} />
  <Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
like image 26
Sabish.M Avatar answered Oct 10 '22 15:10

Sabish.M