Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)); 

     }
like image 570
Vishal Patoliya ツ Avatar asked Feb 11 '26 06:02

Vishal Patoliya ツ


1 Answers

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));

     }
like image 111
Rishabh Rawat Avatar answered Feb 15 '26 18:02

Rishabh Rawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!