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

Viewed 22860

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?

4 Answers

You get a promise as error because you need to have await in your function call too. For example please find my general class and how I call it later in another call.

import AsyncStorage from "@react-native-community/async-storage";

const storageSet = async(key, value) => {
    try {
      await AsyncStorage.setItem(key, value);
    } catch(error) {
      console.log(error);
    }
}

const storageGet = async(key) => {
  try {
       const result = await AsyncStorage.getItem(key);
       console.log(result);
       return result;
    } catch(error) {
      console.log(error);
    }
}

export { storageSet, storageGet };

when I call them note the await keyword

 let value = await storageGet("somekey")
 if (value === null || value === undefined ) {
   //no value set in storage
 }
Related