Home > Software engineering >  initialRouteName of react-navigation does not work as expected
initialRouteName of react-navigation does not work as expected

Time:12-07

I am using react-navigation v5, I have the following code to open the screen based on if user is logged in or not.

<Stack.Navigator
        
        initialRouteName={phone?.length>0 ? data?.accountType === 1 ? "Seller" : data?.accountType === 0 ?  "Buyer" : "SignIn": "SignIn"}
        headerMode="screen"
        screenOptions={{
          headerShown: false,
        }}>
..........
 </Stack.Navigator>

And the phone data and data?.accountType is coming from AsyncStorage inside my componentDidMount() . This is done to open Seller/Buyer page when he is already logged in or SignIn page when he is not logged in. But it always takes me to SignIn page. Is it that before the componentDidMount() gets me the data from AsyncStorage, initialRouteName is already run and thus both phone and data?.accountType are null?

CodePudding user response:

This is simple way you can achieve the result like

constructor(props) {
    super(props)
    this.state = {
      initialRouteName: null,
    }
  }

  render() {
    const layout = this.Layout(this.state.initialRouteName);
    return (layout);
  }

  /** Layout */
  Layout =(initialRouteName)=> {
    if (initialRouteName !== null) {
      return (
        <NavigationContainer>
          <MainStack.Navigator initialRouteName={initialRouteName}>
            <MainStack.Screen name={"screen1"} component={screen1} />
            <MainStack.Screen name={"screen2"} component={screen2} />
          </MainStack.Navigator>
        </NavigationContainer>
      );
    } else {
      return (<View></View>);
    }
  }

  componentDidMount() {
    this.setState({initialRouteName: condition ? "screen1" : "screen2"});
  }
  • Related