I am trying to implement a react navigation authentication flow where there are total three screens and two screen of them are in Authentication ( Login Screen and Registration Screen ) which are used to authenticate a user and the other one is Home Screen ( Feed Screen ) which shows the application's home.
Authenication Screens are in a stack navigator which is AuhenticationNavigation and the home screen is in the HomeScreenNav stack navigator. I have these two stack navigator which are used to navigate. As in the Code Snippet.
The logic I want to implement is that after successful login the screen should navigate to Feed Screen and in Feed Screen I have a logout function which is used to logout and change the persistent state which is isLoggedIn to know that a user is logged in or not.
const RootStack = createStackNavigator();
class AuthenticationNavigation extends Component {
render() {
return(
<RootStack.Navigator headerMode='none'>
<RootStack.Screen name='Login' component={Login}/>
<RootStack.Screen name='Register' component={Register} />
</RootStack.Navigator>
);
}
}
class HomeScreenNav extends Component {
render() {
return(
<RootStack.Navigator headerMode='none'>
<RootStack.Screen name='Feed' component={HomeScreen} />
</RootStack.Navigator>
);
}
}
Two ways I tried to resolve it: 1 :-
<NavigationContainer>
{ this.state.isLoggedIn ? (
<HomeScreenNav />
) : (
<AuthenticationNavigation />
) }
</NavigationContainer>
Above Code snippet shows me Feed Screen is the isLoggedIn is true and evaluates to Authentication Screen is the it is false. But what if I want to navigate to the Auth Screens after a successfull logout in Feed Screen. I have also the tried the react navigation authentication flow from navigation docs but I am not able to resolve my error.
2:-
<NavigationContainer>
<RootStack.Navigator
initialRouteName={ (this.state.isLoggedIn == true) ? 'Home' : 'Auth' }
headerMode='none'
>
<RootStack.Screen
name='Home'
component={HomeScreenNav}
/>
<RootStack.Screen
name='Auth'
component={AuthenticationNavigation}
/>
</RootStack.Navigator>
</NavigationContainer>
Here is the process of retrieving the state which is isLoggedIn.
constructor(props) {
super(props);
this.state = {
tokenId: '',
isLoggedIn: false,
}
}
componentDidMount = async () => {
const token = await AsyncStorage.getItem('token');
this.setState({tokenId: token});
this.setState({isLoggedIn: !Object.is(this.state.tokenId, null)});
await AsyncStorage.setItem('isLoggedIn', this.state.isLoggedIn ? 'Y' : 'N');
console.log(this.state.tokenId, this.state.isLoggedIn);
}
Request: Please provide a proper solution not any documentation links because I have searched for this problem many times on many platforms.