4
votes

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

4
const mobileNumber = AsyncStorage.getItem('mobileno', (err, MobileNumber) => { let abc = MobileNumber; return abc }) be careful though mobileNumber might not exist as this is a callback, you should use it with await async - Rinor Dreshaj

4 Answers

4
votes
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.

3
votes

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
  }
}
2
votes

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

0
votes

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