Issue
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
Solution
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.
Answered By - RDardelet
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.