0
I have an application in React Native with the initial route pointing to the Authloadingscreen screen that checks if the user is logged in and redirects to Login or Home, as the user is not logged in, the expected result was that Authloadingscreen redirects to the Login screen, but this does not happen, the application remains in Authloadingscreen without doing the expected redirection.
Auth Loading Screen
import React, { Component } from "react";
import {
View,
ActivityIndicator,
StatusBar,
Dimensions
} from "react-native";
import {getToken} from '../../services/AuthService';
import styles from "./styles";
import {
NavigationParams,
NavigationScreenProp,
NavigationState,
} from 'react-navigation';
const width = Dimensions.get("screen").width;
interface Props {
navigation: NavigationScreenProp<NavigationState, NavigationParams>;
}
export default class Login extends Component<Props> {
constructor(props: any) {
super(props);
this._bootstrapAsync();
}
_bootstrapAsync = async () => {
const userToken = getToken();
this.props.navigation.navigate(userToken ? 'Home' : 'Login');
};
render() {
return(
<View>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
Authservice
import AsyncStorage from '@react-native-community/async-storage';
export const setToken = (value: string) => AsyncStorage.setItem("TOKEN", value);
export const removerToken = () => AsyncStorage.removeItem('token');
export const getToken = async () => {
return await AsyncStorage.getItem('token');
}
Routes
import {createStackNavigator, createAppContainer} from 'react-navigation';
import Login from './screens/login/Login';
import AuthLoadingScreen from './screens/login/AuthLoadingScreen';
import Home from './screens/home/Home';
export const LoginRoute = createStackNavigator({
Login: {
screen: Login,
navigationOptions: {
header: null
}
}
});
export const HomeRoute = createStackNavigator({
Login: {
screen: Home,
navigationOptions: {
headerLeft: null
}
}
});
const AppContainer = createAppContainer(
createStackNavigator({
AuthLoadingScreen: {
screen: AuthLoadingScreen
},
LoginScreen: {
screen: LoginRoute
},
HomeScreen: {
screen: HomeRoute
}
},
{
initialRouteName: 'AuthLoadingScreen',
}
));
export default AppContainer;
Why use 3 Navigator stack? Wouldn’t 1 be enough? You can use a main Navigator switch to change the login screen to the home screen.
– Luis Eduardo
Yeah, there’s really no need, then I fix it in the code
– Juliana Marques