Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to check whether a key is available in AsyncStorage with AsyncStorage.getItem('key_name'). If the key is not available it is not returning null, it still returns following promise object:

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

My function for getting data is as bellow:

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 can I check whether a key exists in AsyncStorage or not?

like image 697
Mostafiz Rahman Avatar asked May 22 '17 11:05

Mostafiz Rahman


3 Answers

You need to add async await, or add .then to the result

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
    }
}
like image 187
Sagar Khatri Avatar answered Sep 24 '22 15:09

Sagar Khatri


Like the name says, it's async. So you have to:

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

If needed, you can play either with local state or some application state management library.

like image 45
Samuli Hakoniemi Avatar answered Sep 20 '22 15:09

Samuli Hakoniemi


AsyncStorage is async... so, you need to call it this way:

checkUserSignedIn(callback){
  AsyncStorage.getItem('user', (err, result) => {
    if (!err && result != null){
        // do something 
    }
    else {
        // do something else
    }
    callback(result);
  });
}
like image 4
UXDart Avatar answered Sep 21 '22 15:09

UXDart