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;
}
}
Related
When I try to login to Facebook in expo android app, getting the following error
null is not an object (evaluating 'LoginManager.logInWithPermissions')
const SignInwithFB = async () => {
try {
await LoginManager.logInWithPermissions(["public_profile", "email"]);
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
return;
}
const facebookCredential = FacebookAuthProvider.credential(data.accessToken);
const auth = getAuth(firebase);
const response = await signInwithCredential(auth, facebookCredential);
console.log(response);
} catch (e) {
console.log(e);
}
}
installed by following this instructions: https://www.npmjs.com/package/react-native-fbsdk-next
Check Expo installation section in npm install page, make sure you have implemented the instruction
const SignInwithFB = async () => {
try {
const loginManagerResult = await LoginManager.logInWithPermissions(["public_profile", "email"]);
if(loginManagerResult) {
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
return;
}
const facebookCredential = FacebookAuthProvider.credential(data.accessToken);
const auth = getAuth(firebase);
const response = await signInwithCredential(auth, facebookCredential);
console.log(response);
}
} catch (e) {
console.log(e);
}
}
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);
}
};
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.
i'm trying to use this kind of structure.
I have my axios calls in a service file and then call them in vue files.
So i have this js file
const DashboardService = {
getStationList() {
let url = '/api/stations/list'
ApiService.get(url) //ApiService is an Axios wrapper
.then(response => {
console.log(response.data) //data are logged, function is called
response.data
})
}
}
export default DashboardService
Then in the Vue File i have this:
import DashboardService from '#/_services/admindashboard.service'
export default {
methods: {
getMarkers() {
let result = DashboardService.getStationList()
console.log(result) //undefined
}},
mounted() {
this.getMarkers()
}
}
I can't understand why result is undefined because che getStationList() function gets called... when the component is mounted the functions should have returned the response... how can i solve this situation?
getStationList is an async function, so you'll need to await it's result (or use then). For example:
async mounted() {
this.markers = await DashboardService.getStationList();
},
Also see this question for more details.
Next, you are missing a return in the implementation of getStationList.
const DashboardService = {
getStationList() {
const url = '/api/stations/list';
ApiService.get(url).then(response => {
return response.data;
});
},
};
or perhaps:
const DashboardService = {
async getStationList() {
const url = '/api/stations/list';
try {
const response = await ApiService.get(url);
return response.data;
} catch (error) {
console.error(error);
return [];
}
},
};
The result is undefined because getStationList is not returning anything.
You can consider turning your api call into an async function that returns the result.
const DashboardService = {
async getStationList() {
let url = '/api/stations/list';
return ApiService.get(url);
}
}
export default DashboardService
And in your component
methods: {
async getMarkers() {
let result = await DashboardService.getStationList();
console.log(result);
}
},
If you don't want to use the async await syntax. You can return a the promise from your service and utilize the result on your component, as so:
methods: {
getMarkers() {
DashboardService.getStationList().then(result => {
console.log(result);
});
}
},