I've been trying to get the value in the AsyncStorage using getItem() method.
I've created one switch navigator. which is as follows.
export const AuthNavigator = createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen, // Loading screen
App:DrawerNavigator, //screens with drawer navigator
Auth: AuthStack, // login screen
},
{
initialRouteName: 'AuthLoading',
}
);
I've set AuthLoading as initial route. Below is my code of AuthLoadingScreen.
export default class AuthLoadingScreen extends React.Component {
constructor(props) {
super(props);
this._promiseHandling();
}
_promiseHandling = () => {
AsyncStorage.getItem("userToken").then((value) => {
console.log(value);
if(value!=undefined){
this.props.navigation.navigate("App");
}
else{
this.props.navigation.navigate("Auth");
}
})
.catch(res => {
console.log(res);
});
}
// Render any loading content that you like here
render() {
return (
<View style={styles.container}>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
So, Initially I am checking for the value of the userToken from AsyncStorage. if It is there, I am navigating to App. If it is not there then I am navigation to login screen.
App behavior should be as above.
But when the app is loading, it always stuck at AuthLoadingScreen. I tried to debug the code where I am fetching the userToken from asyncstorage, but it is strange for me that control is going to the function _promiseHandling but after that it is not going in then or catch block. I've refer 5-6 examples to read value from async storage and handling its promise.
I've even tried following way but still it is not working for me. React Native AsyncStorage getItem returns promise not value
async _getStorageValue(){
var value = await AsyncStorage.getItem('ITEM_NAME')
return value
}
What can be the reason behind this?
Try this.
export default class AuthLoadingScreen extends React.Component {
constructor(props) {
super(props);
this._promiseHandling();
}
_promiseHandling = async () => {
try {
const token = await AsyncStorage.getItem('userToken');
if (token)
this.props.navigation.navigate("App");
else
this.props.navigation.navigate("Auth");
} catch (error) {
console.log(error);
}
}
// Render
}
Make sure you have properly imported AsyncStorage
before using it, and that you have access to device storage. Also, make sure your AuthLoadingScreen
has received the navigation
prop before you can call it.
If the problem persists, post the error here.