I'm trying to get a single value kept in my device by a AsyncStorage.setItem(KEY, VALUE);.
I have this localStorage.js file to manage local data
import React from 'react';
import { AsyncStorage } from 'react-native';
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 };
In login.js file I call these functions passing the parameters. It saves right. But when I try to getItem() values I have two distinct returns, a promise AND a single value. Follow:
console.log(result) whithin storageGet('key'), it's what I want.
57d7bc714b269533
1
ASUS_Z00AD
1.0
null
1
console.log(result) out storageGet('key') function. In main.js, when I call it.
{login: "Hh", senha: "Hu", imei: Promise, tipo: Promise, modelo: Promise, …}
imei:
Promise {_40: 0, _65: 1, _55: **"57d7bc714b269533"**, _72: null}
login: "Hh"
mobile_key:
Promise {_40: 0, _65: 1, _55: **null**, _72: null}
mobile_push:
Promise {_40: 0, _65: 1, _55: **"1"**, _72: null}
modelo:
Promise {_40: 0, _65: 1, _55: **"ASUS_Z00AD"**, _72: null}
senha: "Hu"
tipo:
Promise {_40: 0, _65: 1, _55: **"1"**, _72: null}
versao:
Promise {_40: 0, _65: 1, _55: **"1.0"**, _72: null}
__proto__: Object
PS.: some items up there is not a return from getItem().
Why does not it just return the single value?
getItem() returns a single value AND a promise.
AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage. It is recommended that you use an abstraction on top of AsyncStorage instead of AsyncStorage directly for anything more than light usage since it operates globally.
Async Storage can only return string data, so in order to use number or object we have to first converts it from string . To get value from asyncstorage, React native asyncstorage provide getItem() method, it will expect storage key and return value .
Since storageGet
returns a promise, you need to also use await anywhere you use it:
const value = await storageGet(key);
AsyncStorage saves data only as strings. You just need to use JSON.stringify() when saving and JSON.parse() when retrieving.
AsyncStorage.getItem('key')
.then((value) => {
const data = JSON.parse(value);
console.log('name is ', data.name);
});
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