Reputation: 3123
I'm building a mobile app in React Native of which auth process is like Whatsapp.I want to set the initialRoute
to 'Signup' if there is no token in AsyncStorage
and dashboard
if token is present.I tried this with the following code, but it always points me to dashboard
even though there is no token in AsyncStorage
.
Drawer
import { AsyncStorage } from 'react-native'
import Signup from '../screens/SignupScreen'
import CustomDrawer from './CustomDrawer'
const DrawNavigator = createDrawerNavigator({
Dashboard: { screen: Home },
Signup: { screen: Signup},
},{
initialRouteName: AsyncStorage.getItem('token') ? 'Dashboard' : 'Signup',
contentComponent: CustomDrawer,
drawerOpenRoute: 'drawerOpen',
drawerCloseRoute: 'drawerClose',
drawerToggleRoute: 'drawerToggle'});
export default DrawNavigator;
EDIT
async function checkToken(){
var token = await AsyncStorage.getItem('token')
return token ? true : false
}
initialRouteName: checkToken() ? 'Dashboard' : 'Signup',
But the app stills gives access to Dashboard
even it there is no token stored
Upvotes: 0
Views: 877
Reputation: 1
if you directly call the async funtion then this will always return promise that means true.that's why you get the true condition always.
Upvotes: 0
Reputation: 564
AsyncStorage works asynchronously, therefore the expression that is interpreted in your condition is the resulting Promise object from the getItem function.
You could try to use the await
statement to block the execution until you know if there is a token. This is not reccomended because you'll be blocking the initialisation of your app.
You can also try to have a default route that will check for a token in the componentDidMount and then redirect based on the result.
Side note:
AsyncStorage imported from "react-native"
is now deprecated and will be removed in a future release of React-Native. Consider installing "@react-native-community/async-storage"
instead.
Upvotes: 2
Reputation: 290
Asyncstorage.getItem() is an asynchronous call. So you have to use async await.
Upvotes: 0