Reputation:
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
Upvotes: 6
Views: 11802
Reputation: 2533
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.
_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
}
}
Upvotes: 3
Reputation: 2065
import {AsyncStorage} from 'react-native';
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
Upvotes: 2
Reputation: 950
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.
Upvotes: 6