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

Mostafiz Rahman picture Mostafiz Rahman · May 22, 2017 · Viewed 17.8k times · Source

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?

Answer

Sagar Khatri picture Sagar Khatri · May 22, 2017

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
    }
}