Vishal Patoliya ツ
Vishal Patoliya ツ

Reputation: 3238

How to use async/await to retrieve value from AsyncStorage in react native by using function

I have created prefsManager.js - Use for storing and retrieve data from AsyncStorage but I have faced a problem like when print log it return always undefined because of it is Async but I want to print the actual value in a log by the call of the function.

import { AsyncStorage } from 'react-native';
import prefskey from '../utils/constants/prefskeys';

const setValue = async (key, value) => {
    await AsyncStorage.setItem(key, value);
}

const getValue = async (key) => {
    let value = '';
    try {
        value = await AsyncStorage.getItem(key) || 'none';
    } catch (error) {
        // Error retrieving data 
        console.log(error.message);
    }
    return value;
};

const prefsmanager = {
    setValue,
    getValue
}
export default prefsmanager; 

I have used this in my Home.js when button press I'm calling this method.

_handlePress() {

        await prefsManager.setValue(prefskey.username, this.state.username)

        console.log("username =>>", await prefsManager.getValue(prefskey.username)); 

     }

Upvotes: 3

Views: 3177

Answers (3)

user10916608
user10916608

Reputation:

Actually, it is like localStorage in the web but with a little difference. in getting the item it acts asynchronously. pay attention to below:

AsyncStorage.setItem('key', value);

But in getting it is like below:

AsyncStorage.getItem('key')
  .then( value => console.log(value) );

Upvotes: 2

mini gondaliya
mini gondaliya

Reputation: 31

  1. Set value in storage
AsyncStorage.setItem('data','Read Data')
  1. Get value from storage
constructor(props) {
    super(props)       

    this.state = {};
    let self=this;

    //this function is called everytime , when you visit this screen.
    this.__didFocusSubscription = this.props.navigation.addListener('didFocus',payload => {
        AsyncStorage.getItem('data').then((value)=>{
            if(value==null){
                self.setState({count:'no data found'})
            }
            else{
                self.setState({count:value})
            }
        })
    });       
}

Upvotes: 3

Rishabh Rawat
Rishabh Rawat

Reputation: 859

You need to use async keyword on your function like this.

    import { AsyncStorage } from 'react-native';
import prefskey from '../utils/constants/prefskeys';

const prefsnamager = {

    setValue: function (key, value) {
        AsyncStorage.setItem(key, value)
    },

    getValue: async (key) => {
        let value = '';
        try {
            value = await AsyncStorage.getItem(key) || 'none';
        } catch (error) {
            // Error retrieving data
            console.log(error.message);
        }
        return value;
    }
}
export default prefsnamager;

calling function

_handlePress = () => {
        prefsManager.setValue(prefskey.username, this.state.username)

        console.log("username =>>" , prefsManager.getValue(prefskey.username));

     }

Upvotes: 4

Related Questions