React Native getItemAsync Returns Promise - react-native

I am writing a storage class as such:
//Fallback if SecureStore fails
let data = {};
import * as SecureStore from 'expo-secure-store';
const Storage = {
set: async function (key, value) {
try {
console.log("Setting Item");
console.log(key);
console.log(value);
return await SecureStore.setItemAsync(key, value);
} catch (e) {
//fallback if set cookie fails
data[key] = value;
}
},
get: async function (key) {
try {
console.log("Gettimg Item");
console.log(key);
let result = await SecureStore.getItemAsync(key);
if (result) {
return await result;
}
return null;
} catch (e) {
console.error(e);
value = data[key];
return value;
}
}
export default Storage;
And Storage.set is called as such:
function() {
Storage.set("some_key", "some_value");
}
And here is an output of the console.log
Setting Item
user_id
4ce9dse7-650a-4ff5-955d-466a640de2c4
Setting Item
user_first_name
John
Setting Item
user_last_name
Doe
So apparently the items are being set. But each time I use the get function Storage.get(x), I get a promise back:
Promise {
"_A": null,
"_x": 0,
"_y": 0,
"_z": null,
}
What am I doing wrong here? I am using await twice but still returns a promise.

Related

Using AsyncStorage to show screen on first login

I'm trying to only show the disclosure screen the first time the user logs in by using AsyncStorage. Currently getData is returning a Promise and it goes straight to the landing screen on first login.
Could I get some help to get this functioning the way I want it to?
This is my login handler:
const key = 'key';
const storeData = async () => {
try {
await AsyncStorage.setItem('key', 'true');
} catch (error) {
// saving failed
console.log(error.message);
}
};
const getData = async key => {
let value = '';
try {
value = await AsyncStorage.getItem(key);
return JSON.parse(value);
} catch (e) {
console.log(error.message);
}
};
const _loginHandler = () => {
if (userName == '' || password == '') {
console.log('gagagagagagagagagagagagagagagagag');
} else {
setShowLoading(true);
const payload = {userName: userName.trim(), password: password.trim()};
setUserName('');
setPassword('');
_UserLoginHandler(payload).then(data => {
setShowLoading(false);
if (data.error) {
GlobalShowSnackBar(data.error);
} else {
setTimeout(() => {
setUserId(data);
//props.navigation.replace(getData("key")?'Landing':'Disclosure')
console.log('Key Value ' + JSON.stringify(getData('key'))); <-- this outputs Key Value {"_U":0,"_V":0,"_W":null,"_X":null}
if (getData('key')) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
}, 500);
}
});
}
};
I got it to work with
getData('key').then(val => {
if (val) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
});

I am getting `Can not use keyword 'await' outside of a async function` within an Async function.. React-native

I am having an issue with async await for my AsyncStorage function within my React-native application. The error I'm getting is:
Can not use keyword 'await' outside of a async function
As you can see below, it's obvious that await is within the function. What am I doing wrong to get this error?
_retrieveData = async function (location) {
try {
var index = await AsyncStorage.getItem(location, (err, result) => result).then(result => result).catch(error=>console.log(error))
if (index !== null) {
return JSON.parse(index)
}
} catch (error) {
return null
}
};
_storeData = async function(location, value) {
try {
await AsyncStorage.set(location, JSON.stringify(value));
} catch (error) {
console.log(error)
}
};
Use ES6 arrow functions
const _retrieveData = async location => {
try {
let index = await AsyncStorage.getItem(location)
if (index !== null) {
return JSON.parse(index);
}
} catch (error) {
return null;
}
};
const _storeData = async (location, value) => {
try {
await AsyncStorage.set(location, JSON.stringify(value));
} catch (error) {
console.log(error);
}
};
Make them as an arrow functions
_retrieveData = async location => {
try {
let index = await AsyncStorage.getItem(location)
if (index !== null) {
return JSON.parse(index);
}
} catch (error) {
return null;
}
};
_storeData = async (location, value) => {
try {
await AsyncStorage.set(location, JSON.stringify(value));
} catch (error) {
console.log(error);
}
};

How to use AsyncStorage to store array in React Native

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
}
};

React native AsyncStorage bad response

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.

Can't get data out of Axios

Can't get my data from the request out of Axios. My console log prints the correct but when I try to set it to a variable or return it I get nothing.
static getGroupByID(groupID) {
var self = this;
var group = '';
axios.post((GRAPHQL_END_POINT), {
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}`enter code here`
})
.then(res => {
console.log(res.data.data.getGroup.name);
self.group = res.data.data.getGroup.name;
})
.catch(err => console.log(err))
return group;
}
static getGroupByID(groupID) {
var self = this;
var group = '';
return axios.post((GRAPHQL_END_POINT), { <-- Return your promise
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}`enter code here`
})
.then(res => {
console.log(res.data.data.getGroup.name);
return res.data.data.getGroup.name; <--- Return your data and use getGroupById(...).then(...)
})
.catch(err => console.log(err))
}
The query is async, your function returns an empty group = '', set the value in state or use await. The function returns before the query finish, you can for the query to finish using async/await.
static async getGroupByID(groupID) {
try {
const res = await axios.post(GRAPHQL_END_POINT, {
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}
});
const { data } = await res;
return data;
} catch (error) {
console.log(error);
}
}
Or you can just return the promise and handle it where you are calling the function.
static getGroupByID(groupID) {
return axios.post(GRAPHQL_END_POINT, {
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}
});
}