Get item value from AsyncStorage in react-native - react-native

I am a beginner and still try to learn to react native so help me!
I want to access AsyncStorage.getItem value outside the function.
I will further explain via code
This is my code :
import {AsyncStorage} from 'react-native';
set that value on screen1
AsyncStorage.setItem('mobileno', JSON.stringify(MobileNo));
try to get that value on screen 2
AsyncStorage.getItem('mobileno', (err, MobileNumber) => {
let abc = MobileNumber;
console.log("abc value " + abc)
})
let { MobileNo } = abc;
console.log({MobileNo})
I want to access that abc value outside the function as let { MobileNo } = abc; but it shows the error!
note : [console.log("abc value " + abc) works perfectlly ]
Error
can't find variable abc
question
So, how can I access that abc or that AsyncStorage value for the whole page [outside that function]; Because I want to use that value in other function too!
In short, I want that stored value in AsyncStorage to use it in other function.
Thank you for contributing your precious time

constructor(props) {
super(props);
this.state = {
mobileNumber: '',
};
}
componentDidMount() {
AsyncStorage.getItem('mobileno').then((mobileNo) => {
if(mobileNo){
this.setState({mobileNumber: mobileNo});
console.log(this.state.mobileNumber);
}
});
}
render() {
return(
<View>
<Text>{this.state.mobileNumber}</Text>
</View>
);
}
In this case async/await is not necessary because .then() is only called after the getItem() function is done fetching the item.

In your code abc is called out of scope. abc is only declared in your callback. An alternative can be to create a class method that returns that data. I personally find the async/await syntax much cleaner and easier understand the .then() chains.
docs show an example of this
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('mobileno');
if (value !== null) {
// We have data!!
console.log(value);
return value;
}
} catch (error) {
// Error retrieving data
}
}

import {AsyncStorage} from 'react-native';
Above AsyncStorage is Deprecated, Moved to React-Native-Community
you can use now
1 :- yarn add #react-native-community/async-storage
2 :- react-native link #react-native-community/async-storage
Code :-
import AsyncStorage from '#react-native-community/async-storage';
storeData = async () => {
try {
await AsyncStorage.setItem('#storage_Key', 'stored value')
} catch (e) {
// saving error
}
}
getData = async () => {
try {
const value = await AsyncStorage.getItem('#storage_Key')
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}
Link :- https://www.npmjs.com/package/#react-native-community/async-storage

use the link
https://github.com/react-native-community/async-storage
Install
$ yarn add #react-native-community/async-storage
Link
React Native 0.60+
CLI autolink feature links the module while building the app.
React Native <= 0.59
$ react-native link #react-native-community/async-storage
Note For iOS using cocoapods, run:
$ cd ios/ && pod install
See docs for manual linking guide
Upgrading to React Native 0.60+
New React Native comes with autolinking feature, which automatically links Native Modules in your project. In order to get it to work, make sure you unlink Async Storage first:
$ react-native unlink #react-native-community/async-storage
Usage
Import
import AsyncStorage from '#react-native-community/async-storage';
Store data
storeData = async () => {
try {
await AsyncStorage.setItem('#storage_Key', 'stored value')
} catch (e) {
// saving error
}
}
Read data
getData = async () => {
try {
const value = await AsyncStorage.getItem('#storage_Key')
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}

Related

#react-native-async-storage/async-storage getItem is giving value as false

I am trying to access react-native Async storage in a different file from where it has been set. In the same file where it is being set , i am able to get the value. but in the different file i am getting "false" as the value.
Any help would be greatly be appreciated.
import AsyncStorage from '#react-native-async-storage/async-storage';
const getData = async () => {
console.log("fetching data from asyncstorage")
try {
const value = await AsyncStorage.getItem('userToken'); << retuning false
if(value !== null) {
console.log(value);
token.token=value;
}
} catch(e) {
console.log(e);
}
}
const callfunction=()=>{
getData();
}
This is how i was able to make it work,If somebody got a better solution please do post here,
As operation with AsyncStorage are happening in async manner, meaning the main thread will not wait for the function call to be coompleted, i found it best to call the function way before i needed it and keep it stored.
In order to acheive this i used a react hook "useEffect" this is similar to springboot alternative #PostConstruct, meaning "useEffect" will be called the moment you are navigate to the page. So the code looks something like this.
import AsyncStorage from '#react-native-async-storage/async-storage';
import React,{useEffect} from 'react';
const [token, setToken] = React.useState({
token: "",
});
const getData = () => {
console.log("fetching data from asyncstorage")
AsyncStorage.getItem('userToken').then((value) => {
console.log("token : "+ value);
token.token=value;
}).done();
}
useEffect(() => {
if(token.token=="")
{
getData();
}
});
If someone finds any good blog or video supporting this do post it here, also if my explanation, is deviating from technical aspect please help me understand it better.

The `testDeviceID` prop of AdMobBanner is deprecated. Test device IDs are now set globally. Use AdMob.setTestDeviceIDAsync instead

I've recently been producing an app on a real-native basis. I also put in an ad banner using Google's admob There is no advertisement that used to appear until a few days ago.
Setting the admob props below will result in an error.
<AdMobBanner
bannerSize="banner"
adUnitID="ca-app-pub-#######"
testDeviceID="EMULATOR"
servePersonalizedAds = {true}
onDidFailToReceiveAdWithError={this.bannerError}
/>
The errors are as follows.
The `testDeviceID` prop of AdMobBanner is deprecated. Test device IDs are now set globally. Use AdMob.setTestDeviceIDAsync instead.
I'd appreciate it if you could help me.
I had the same problem, They should update the information on the Expo site. I believe this should work for the banner as well.
Import:
import {
setTestDeviceIDAsync, //<--- I forgot this first time
AdMobInterstitial
}from 'expo-ads-admob';
init after mount:
componentDidMount(){
this.initAds().catch((error) => console.log(error));
}
initAds = async () => {
AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/1033173712') //test id
await setTestDeviceIDAsync('EMULATOR');
}
Trigger this function from a button or what ever you like:
_openInterstitial = async () => {
try {
this.setState({ disableInterstitialBtn: true })
await AdMobInterstitial.requestAdAsync()
await AdMobInterstitial.showAdAsync()
} catch (error) {
console.error(error)
} finally {
this.setState({ disableInterstitialBtn: false })
}
}

How to save history of component in react native using react native router flux

I am using react native router flux in android project for routing when i jump from one component to another than the history of last component is remove from stack i want to store components history please anyone.
instead of jump you can use
Action.keynameofyournextpage()
ex to go to page1 to page2
can use
Actions.page2()
in page 1
If you want to save a record of the components, use the AsyncStorage module to save them.
Example
import {AsyncStorage} from 'react-native';
//set data
_storeData = async () => {
try {
await AsyncStorage.setItem('componenthistory', componenthistory);
} catch (error) {
// Error saving data
}
};
...
//get data
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('componenthistory');
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
};

How to stored a variable in asyncstorage?

I currently learning react-native.
I am trying to stored a variable into asyncstrorage in scriptone.js and calling it in scripttwo.js
But i failed to stored the variable in scriptone.js
What i have import in scriptone.js:
import React, { Component, BackAndroid } from "react";
import { AsyncStorage } from 'AsyncStorage';
import { View, Text, StyleSheet, Button, Image, TouchableOpacity, TextInput, Alert} from "react-native";
This is part of my code in scriptone.js
class SettingScreen extends Component {
state = {
a: '70',
b: '',
c: '',
};
onPressButton = () => {
if (this.state.a == this.state.aa) {
this.setState({ b: this.state.a });
this.storeData();
}
else {
Alert("Try Again");
}
}
storeData(){
const {a} = this.state;
let mynum : a;
AsyncStorage.setItem('array',mynum)
Alert("Saved");
}
...
The error display :
"undefined is not an object(evaluating '_AsyncStorage.AsyncStorage.setItem')
May I know what the problem?
Thank you.
AsyncStorage
Usually to use AsyncStorage you first import it at the top of you file, the documentation says that you should import it as follows:
import { AsyncStorage } from 'react-native';
Which you can see here https://facebook.github.io/react-native/docs/asyncstorage
Obviously you should remove the previous import statement
import { AsyncStorage } from 'AsyncStorage';
as leaving it in will cause name conflicts.
Saving to AsyncStorage
Saving to AsyncStorage is an asynchronous task so you should use an async/await function that means you should update your storeData() function. You can see the documentation https://facebook.github.io/react-native/docs/asyncstorage for how you should do this.
storeData = async () => {
const {a} = this.state;
let mynum = a;
try {
await AsyncStorage.setItem('array', mynum)
Alert("Saved");
} catch (err) {
console.warn(err);
}
}
Setting state
Next it looks like you could be getting yourself into a race condition when you're setting the state. It takes time for setState to set the item to state. So when you call
this.setState({ b: this.state.a });
the state may not have actually been set by the time you call
this.storeData();
leading to the wrong value being stored in AsyncStorage.
To over come this there is a couple of ways you could handle this
Use setState with a callback
Pass the variable to store as a parameter to this.storeData()
Use setState with a callback
This article goes into quite some detail about using setState with a callback https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296 however you could refactor your onPressButton to something like this
onPressButton = () => {
if (this.state.a == this.state.aa) {
this.setState({ b: this.state.a }, async () => { await this.storeData(); });
} else {
Alert("Try Again");
}
}
This will guarantee that this.storeData() won't be run until the state has been updated.
Pass the variable to store as a parameter
This requires refactoring the storeData() function to take a parameter
storeData = async (mynum) => {
try {
await AsyncStorage.setItem('array',mynum)
Alert("Saved");
} catch (err) {
console.warn(err);
}
}
Now to use this function we have to update your onPressButton, Notice that we pass the value that we want to store to storeData that means we no longer have to access it from state inside storeData
onPressButton = async () => {
if (this.state.a == this.state.aa) {
this.setState({ b: this.state.a });
await this.storeData(this.state.a);
} else {
Alert("Try Again");
}
}
Retrieving from AsyncStorage
This is also an asynchronous task and requires an async/await. To get the string that you stored all you have to do is pass the correct key to the retrieveData function
retrieveData = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
if (value !== null) {
// We have data!!
console.log(value);
// do something with the value
}
} catch (error) {
// Error retrieving data
}
}

How to get the device token in react native

I am using react-native 0.49.3 version, My Question is how to get the device token in react native for both IOS and Android I tried with this link but it not working for me, right now I tried in IOS. how to resolve it can one tell me how to configure?
I tried different solutions and I've decided to use React Native Firebase.
Here you will find everything about Notifications.
Also, you can use the others libraries that come with Firebase, like Analytics and Crash Reporting
After set up the library you can do something like:
// utils/firebase.js
import RNFirebase from 'react-native-firebase';
const configurationOptions = {
debug: true,
promptOnMissingPlayServices: true
}
const firebase = RNFirebase.initializeApp(configurationOptions)
export default firebase
// App.js
import React, { Component } from 'react';
import { Platform, View, AsyncStorage } from 'react-native';
// I am using Device info
import DeviceInfo from 'react-native-device-info';
import firebase from './utils/firebase';
class App extends Component {
componentDidMount = () => {
var language = DeviceInfo.getDeviceLocale();
firebase.messaging().getToken().then((token) => {
this._onChangeToken(token, language)
});
firebase.messaging().onTokenRefresh((token) => {
this._onChangeToken(token, language)
});
}
_onChangeToken = (token, language) => {
var data = {
'device_token': token,
'device_type': Platform.OS,
'device_language': language
};
this._loadDeviceInfo(data).done();
}
_loadDeviceInfo = async (deviceData) => {
// load the data in 'local storage'.
// this value will be used by login and register components.
var value = JSON.stringify(deviceData);
try {
await AsyncStorage.setItem(config.DEVICE_STORAGE_KEY, value);
} catch (error) {
console.log(error);
}
};
render() {
...
}
}
Then you can call the server with the token and all the info that you need.