Stored objected is:
{
name: 'Chris',
age: 30,
traits: {
hair: 'brown',
eyes: 'brown'
},
};
not able to retrieve value.propertyName.
AsyncStorage.getItem('key').then( (value) => console.log('value ', value, 'name is ', value.name));
output is : value {"name":"Chris","age":30,"traits":{"hair":"brown","eyes":"brown"}} name is undefined.
Please let me know how to retrieve a specific value from promise object
getItem Gets a string value for given key . This function can either return a string value for existing key or return null otherwise. In order to store object value, you need to deserialize it, e.g. using JSON. parse() .
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.
To get value from asyncstorage, React native asyncstorage provide getItem() method, it will expect storage key and return value . Check below examples to get string, number, or object in AsyncStorage. To get number in AsyncStorage we have to first convert it to number using parseInt() method.
Saving the data This method is going to be promise-based, which means you can use the async await syntax with a try-catch block. Passing the identifier STORAGE_KEY as well as the input state variable, the API method AsyncStorage. setItem is going to store the value in storage.
AsyncStorage saves data only as strings. You just need to use JSON.stringify()
when saving and JSON.parse()
when retrieving.
For instance:
AsyncStorage.getItem('key')
.then((value) => {
const data = JSON.parse(value);
console.log('name is ', data.name);
});
Another option is to use some kind of wrapper for AsyncStorage which does this for you, like: https://github.com/jasonmerino/react-native-simple-store
You could do for set the value the following
async setAsyncStorage (key, value) {
try {
await AsyncStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.warn(error);
}
}
And for get the following:
async getAsyncStorage (key) {
try {
const getAsyncStorageData = await AsyncStorage.getItem(key);
const getAsyncStorageParsed = JSON.parse(getAsyncStorageData);
return getAsyncStorageParsed;
} catch (error) {
console.warn(error);
}
}
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