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?
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 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.
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With