I've been looking for answers on stack overflow but so far nothing is working.
I'm using this function(below) to retrieve a simple array since i want to show its contents in the return() function.
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('FavouritesArray');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};
The code does work and it logs the array I want (["Rose","Mojito"]) but i can't figure out how to get the array outside the _retrieveData() function. I've tried returning it (returns a promise) as well as putting it in a global variable and then returning it, but that also just return a promise object.
How do I extract the populated array from this async function?
You can store and retrieve your data like this with AsyncStorage:
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
console.log(error);
}
};
const getData = async key => {
try {
const data = await AsyncStorage.getItem(key);
if (data !== null) {
console.log(data);
return data;
}
} catch (error) {
console.log(error);
}
};
then call getData with the key name like you stored your array wherever you want and set the key to a state array.
await getData("yourarraykey")
.then((data) => data)
.then((value) => this.setState({ yourarraystate: value }))
.catch((err) => console.log("AsyncStorageErr: " + err));
after that in this.state.yourarraystate the value of your fetched array will be available.
~Faded
Related
In my below code, I stored an object in AsyncStorage in React Native, but I have a problem reading it inside {personValue}. I got
Can't find variable personValue
Error. could you help me to run my code?
const storeData = async () => {
try {
const newperson = JSON.stringify(person);
await AsyncStorage.setItem("#Key", newperson);
alert(newperson);
} catch (e) {
}
};
const getData = async () => {
try {
const personValue = await AsyncStorage.getItem("#Key");
if (personValue !== null) {
console.log(JSON.parse(personValue));
return JSON.parse(personValue);
}
} catch (error) {
}
in the console, I can see the object correctly in GetData method
P.S: I found the mistake I made. I parsed the wrong variable.
const getData = async () => {
try {
const personValue = await JSON.parse(AsyncStorage.getItem("#Key"));
if (personValue !== null) {
console.log(personValue);
return personValue;
}
}
I want to get user's current location and set it into AsyncStorage a array. I will do it in the useEffect hook. But the problem is my functions are not working that according to given order. Here are my code
useEffect(() => {
getUserLocation();
setUserLocation();
check();
}, []);
/*Get User's Currunt Location*/
const getUserLocation = () => {
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 15000,
})
.then((location) => {
var lt = location.latitude;
var lg = location.longitude;
setlatitude(lt);
setlongitude(lg);
console.log("getUserLocation", lt, lg);
})
.catch((error) => {
const { code, message } = error;
console.warn(code, message);
});
};
/*Set User's Currunt Location to AsyncStorage*/
const setUserLocation = async () => {
try {
await AsyncStorage.setItem("user_location", JSON.stringify(userLocation));
console.log("setUserLocation", userLocation);
} catch (error) {
console.log("error setting user location");
}
};
const check = () => {
AsyncStorage.getItem("user_location", (err, result) => {
if (result !== null) {
console.log("check", result);
setlatitude(result.latitude);
setlongitude(result.longitude);
} else {
console.log("Data Not Found");
}
});
};
Whenever you use .then you are scheduling your code to run at some point in the future, when the promise has completed. So setUserLocation runs before the then of getUserLocation.
Also, it looks like your getUserLocation set react state, which won't be available until the next render. We use effects to manage this.
// Get the location on mount
useEffect(getUserLocation, []);
// Whenever the location updates, set it into storage
useEffect(() => setUserLocation().then(check), [latitude, longitude]);
I am trying to use AsyncStorage to store simple Profile using React Native.
Here is What I have so far for adding Profile, I tried console.log(contact), but showed nothing.
function AddContact(props) {
const [FName,setFName] = useState('');
const [LName,setLName] = useState('');
const [PNumber,setPNumber] = useState('');
var contact = {
firstname : FName,
lastname : LName,
phonenumber : PNumber
};
const storeContact = async() => {
try {
await AsyncStorage.setItem(
'#MySuperStore:key', JSON.stringify(contact));
} catch (error) {
// Error saving data
}}
For Loading Profile
const loadContact = async () => {
try {
const value = await AsyncStorage.getItem('#MySuperStore:key', JSON.stringify(contact));
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};
Please help.
In order to load the data from the Async Storage, your loadContact method should be:
For Loading Profile
const loadContact = async () => {
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
const json = JSON.parse(value); // this is how you get back the array stored
if (json !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};
AsyncStorage.getItem() only accept one argument that is key. So you have to pass only argument "key" and it will return your data as string:
const value = await AsyncStorage.getItem('#MySuperStore:key');
Or if you want to use this value as array to display something you have to convert it into json.
const loadContact = async () => {
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
if (value !== null) {
// We have data!!
console.log(value);
this.setState({
data: JSON.parse(value);
});
}
} catch (error) {
// Error retrieving data
}
};
Have created React Native app and ned to use AsyncStorage to benefit from it's storage mechanism.
To save in AsyncStorage use code:
_storeData = async (param) => {
try {
let par = JSON.stringify(param);
//await AsyncStorage.setItem(this.key, par);
Utilities.setItem(this.key, par);
this._retrieveData();
} catch (error) {
console.log(JSON.stringify(error));
}
};
To retrieve data:
_retrieveData = async () => {
try {
const value = Utilities.getItem(this.key);
if (value !== null) {
alert('data is new: ' + JSON.stringify(value));
}
} catch (error) {
}
};
And, to setItem and getItem in Utilities partial:
const setItem = (key, value) => {
if (!key || !value) return;
AsyncStorage.setItem(key, value);
};
const getItem = (key) => {
if (!key) return;
var val = AsyncStorage.getItem(key);
return val;
};
Data is being saved, but response I'm getting does not look correctly, as it's a string of 'weird' characters:
{"_40":0,"_65":0,"_55":null,"_72":null}
Does anybody know why I'm getting such answer?
Note that AsyncStorage.getItem is also async - the weird characters represent the promise being returned by getItem.
Use var val = await AsyncStorage.getItem(key); and mark your getItem utility function as async. You'll need to await on any calls to Utilities.getItem and Utilities.setItem as well.
for setting the item i am using this first code.
console.log(ACCESS_TOKEN);
console.log(typeof(ACCESS_TOKEN));
async function setToken() {
try {
await AsyncStorage.setItem('access_token', ACCESS_TOKEN);
} catch (error) {
console.log("token not set")
}
}
setToken();
for getting the item , i am using this code
componentWillMount(){
async function getToken() {
try {
const value = await AsyncStorage.getItem('access_token');
if (value !== null){
console.log(value);
this.setState({ access_token: value });
}
} catch (error) {
console.log( "Error retrieving data")
}
}
getToken();
the result i am getting in first code is
1a61b72b-ee83-43de-9cf9-3fa270ce694d
string
but getting nothing at console at getting code . why ?
You can try this one:
set item using this
AsyncStorage.setItem('access_token', ACCESS_TOKEN);
get item using this
try {
AsyncStorage.getItem('access_token')
.then((value) => {
if (value) {
// you will get your access_token here
}
}).done();
} catch (error) {
console.log(error); // you will get error here
}
To set the item
AsyncStorage.setItem('access_token', ACCESS_TOKEN)
.then(() => {
//your success code
})
.catch((error) => {
//your failure code
})
To get the item
AsyncStorage.getItem('access_token')
.then(access_token=> {
//you will be getting the access token here
})
.catch(err => {
//handle the error
})
Maybe this is what you intended:
async function getToken() {
try {
const value = await AsyncStorage.getItem('access_token');
if (value !== null){
console.log(value);
this.setState({ access_token: value });
}
} catch (error) {
console.log( "Error retrieving data")
}
}
componentWillMount(){
getToken();
}
If instead your code is getting stuck while working with AsyncStorage, there's a well known bug reproducible only in development: https://github.com/facebook/react-native/issues/12830
They only way to bypass it, afaik, it is just to restart the debugger when you get stuck
Remember that setting state during componentWillMount is not the correct way to do it. You should use the constuctor for that
My answer might not directly apply to your case, But I had the same problem as you did with AsyncStorage and It was getting stuck, so this might help other people.
As stated in this answer:
AsyncStorage only takes string as a value and key.
But I was accidentally giving it null (which as you know is considered an object) so it got stuck. So check if you are passing a string value as both the first and second argument to setItem.