How to check if a key exists in AsyncStorage in React Native? getItem () always returns a promise object

I am trying to check if a key is available in AsyncStorage using AsyncStorage.getItem('key_name') . If the key is not available, it does not return null, it still returns the following promise object:

 Promise _45:0 _54:null _65:null _81:1 

My data acquisition function is below:

 checkItemExists(){ let context = this; try { let value = AsyncStorage.getItem('item_key'); if (value != null){ // do something } else { // do something else } } catch (error) { // Error retrieving data } } 

How to check if a key exists in AsyncStorage or not?

+7
javascript react-native react-native-android
source share
3 answers
 async checkUserSignedIn(){ let context = this; try { let value = await AsyncStorage.getItem('user'); if (value != null){ // do something } else { // do something else } } catch (error) { // Error retrieving data } } 
+6
source share

As the name says, it is asynchronous. Therefore you need to:

 AsyncStorage.getItem('user') .then((item) => { if (item) { // do the damage } }); 

If necessary, you can play either in the local state or in the application state control library.

+4
source share

AsyncStorage isync ... so you need to call it like this:

 checkUserSignedIn(callback){ AsyncStorage.getItem('user', (err, result) => { if (!err && result != null){ // do something } else { // do something else } callback(result); }); } 
+2
source share

All Articles