React Native AsyncStorage: Accessing Value from Promise Object - react-native

When I use AsyncStorage.getItem() to retrieve the value (an email address) of a specified key, it returns a Promise object as indicated in the documentation. The value appears in object like so:
{
_45: 0
_54: null
_65: "testuser#test.com"
_81: 1
}
Can I reliably access this value by calling obj._65 or is there another way to accomplish this?

AsyncStorage return a promise. you can use .then for get value
exemple:
AsyncStorage.getItem('key').then((keyValue) => {
console.log(keyValue) //Display key value
}, (error) => {
console.log(error) //Display error
});

Looking at the docs you should be able to do this reliably to retrieve data from your async storage object.:
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
if (value !== null){
// We have data!!
console.log(value._65);
}
} catch (error) {
// Error retrieving data
}
you must use this within a function that is async however or you will get a runtime exception.

Related

AsyncStorage functions just producing garbage in react native

So I implemented this code in a file from the react native docs.
class Storage {
//store data in 'key'
store = async (key, data) => {
try {
await AsyncStorage.setItem(key, data);
} catch (error) {
// Error saving data
console.log(error.message);
}
};
retrieve = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
console.log(error.message);
}
};
}
And this in other I want to use to actually store and retrieve the variables:
strg.store('test', 'testing');
testing = strg.retrieve('test');
I kept getting an error but then looking it up here I figured out my storage output was an object and not a string as I expected. So I used JSON.stringify(***) and this gibberish came out instead of a "testing".
{"_40":0, "_65":0, "_55":null,"_72":null}
edit: I figure out how to use the console to debug and I found out the 'testing' was inside the promise object that comes out of my function. I read a little about async functions and now I want to know how do I extract the values from the promises?
This happened because you are using AsyncStorage - an asynchronous storage system. You have to wait until it done retrieve data from storage to get the proper data.
I think there are two correct ways to get data from your implementation:
Use async with your container function name & await with your function called
async function getData() {
....
let data = await strg.retrieve('test');
console.log("data", data);
}
or simple use .then():
strg.retrieve('test').then((data) => {
console.log("data", data);
// Handle retrieved data
});
Hope that help. :)
This is how i did it and it works like a charm
import { AsyncStorage } from 'react-native';
module.exports = {
retrieve: async (value) => {
try {
let data = await AsyncStorage.getItem(value);
return data;
} catch (err) {
return err;
}
},
store: async (key, value) => {
try {
// stringify the value since value can only be string.
if (typeof (value) === 'object')
value = JSON.stringify(value)
return await AsyncStorage.setItem(key, value);
} catch (err) {
console.log(err)
return err;
}
}
}
Your store and retrieve functions are asyn so you have to use await until the actual task is complete.
So the code should be like below.
await strg.store('test', 'testing');
const testing = await strg.retrieve('test');
The garbage value is a promise so it will be something like the object you got.
If you return value like this you will retrieve it from outside.
const value = await AsyncStorage.getItem(key);
if (value !== null) {
// We have data!!
console.log(value);
return value;
}

React-native sync storage solution

In native iOS code, I could use the NSUserDefaults to store and fetch data, which are sync operations. In react-native the offer is to use AsyncStorage, but I need a solution for sync storing, like NSUserDefaults.
I'm gonna use the result of data fetching to determine which screen to show, but since it's async I always get undefined when trying to fetch the persisted data.
after calling
AsyncStorage.getItem('#MySuperStore:key');
react-native will call native function dependent on your platform in other thread
then it will return a promise to resolve it
,so if call like this
let value = AsyncStorage.getItem('#MySuperStore:key');
value ++;
your value is not valid cause it data will be available later
the correct way to do is :
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
if (value !== null){
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
other way of doing this is
try {
AsyncStorage.getItem('#MySuperStore:key',(value )=>{
if (value !== null){
// We have data!!
console.log(value);
}});
} catch (error) {
// Error retrieving data
}
you could make it asynchronous for example
getData = async () => {
const value = await AsyncStorage.getItem('Yourkey');
this.setState({key: value})
}

Why AsyncStorage getItem is returning null?

export const USER_KEY = "isLoggedIn";
export const phoneVerified = () => AsyncStorage.setItem(USER_KEY, 1);
export const userInfoVerified = () => AsyncStorage.setItem(USER_KEY, 2);
I have used the above functions to store the value and the below one to get the value.
export const isSignedIn = () => {
return new Promise((resolve, reject) => {
AsyncStorage.getItem(USER_KEY)
.then(res => {
console.log("from isSignedIn : "+res); //res is showing null.
if (res !== null) {
resolve(res);
} else {
resolve(0);
}
})
.catch(err => reject(err));
});
};
Why this always returns null? I was trying async/await but still getting null. I think somehow the data is not storing.
I'm afraid you can only store strings. Please refer to this React Native AsyncStorage storing values other than strings and this https://facebook.github.io/react-native/docs/asyncstorage.html#setitem
Thanks.
As answered by #Vishu Bhardwaj AsyncStorage accepts only string. So you can use JSON.stringify() and JSON.parse() in such cases.
I was stuck with this stupid problem for almost one week, no other way that is suggested in all communities worked for me, but then I found something that is built of react-native which its setState() callback function: https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296.
so the only way that I guarantee that it's the only secure way so far is this that u use the setState() function in your promise and everything that you need to run, put them on a function and call it for the setState() callback function , this is only way you can make sure yourself that you neither get null nor never calling the function . Here I'm going to provide an example of it which this.tokeToServer() is my function which it's used as a callback function.
try {
AsyncStorage.getItem('firebase_token',(err,item) => {
if (item) {
this.setState({
firebase_token: item,
}),this.tokenToServer();
}
});
} catch (error) {
console.log("Error retrieving data" + error);
}
As presented by friend Abdu4, I had the same problem for 4 days and searching for different sites and forums. Attempts with async/await and others, even though you should use these options, the one you completed and really worked was to assign the value through setState by callback
try {
AsyncStorage.getItem('TOKEN_KEY',(err,item) => {
if (item) {
setToken({
Token: item,
});
}
});
} catch (error) {
console.log("Error retrieving data" + error);
}

How to parse data from AsyncStorage to <Text>

I am getting the following error when I get data from AsyncStorage:
Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72})
async function setItem(key, value) {
try {
await AsyncStorage.setItem(key, value);
console.log(key, value);
return value;
} catch (error) {
// Handle errors here
}
}
async function getItem(item) {
try {
const value = await AsyncStorage.getItem(item);;
console.log(value);
return value;
} catch (error) {
// Handle errors here
}
}
setVar = setItem('username', 'Name');
getVar = getItem('username');
I am getting the error when outputting the result to:
<Text>{getVar}</Text>
When I check console I get the required output/everything is correct but I cannot render the text to the screen.
Any help or suggestions would be greatly appreciated.
Thanks.
Cross posting from https://forums.expo.io/t/how-to-parse-data-from-asyncstorage-to-text/3417/4
Ah, your function getItem is giving back a Promise, remember that async keyword automatically makes the function return Promise. Hence the error message, can’t put the Promise object in
Suggest you:
Put the string you’ll use in state:
state = {showThisText:''}
in render: {this.state.showThisText}
Then in async componentDidMount, get the data and do a this.setState({showThisText:YOUR_PULLED_STRING})
try it like this it will work,
setVar = await setItem('username', 'Name');
getVar = await getItem('username');
make both of your calling functions async too.

Unable to return token from AsyncStorage in React Native

I am using React Native's AsyncStorage to store an authorization token, which will be returned when needed to use for new http requests. While I can successfully store it and console log it, I am having some trouble returning the value. I want to call it in another window, in the fashion of
var x= LocalDb.getAcessToken();
console.log(x);
However it won,t work.
LocalDb.getAccessToken();
This on the other hand, works when getAcessToken() has console.log in it
exports.storeToken=function(token){
AsyncStorage.setItem('access_token', token);
}
^^^^This function successfully saves the token
exports.getAccessToken=function(){
AsyncStorage.getItem('access_token')
.then((value) => {
if(value) {
console.log(value);
**//I want to return the value here, to use in another function**
}
})
.done();
}
I can not return the value when I use the return(value) . How can I return a value from the promise?
You need to return the getAccessToken function with the promise call. I would also return the promise with the value... like this.
exports.getAccessToken=function(){
return AsyncStorage.getItem('access_token')
.then((value) => {
if(value) {
console.log(value);
return value;
}
})
}