Home > Back-end >  Trying to put AsyncStorage.getItem() inside async/await try/catch nest but returning unexpected stuf
Trying to put AsyncStorage.getItem() inside async/await try/catch nest but returning unexpected stuf

Time:06-16

I have this on React-Native, basically I successfully saved some stuff using AsyncStorage from the LoginScreen. Now I'm trying to access those variables on my HomeScreen using AsyncStorage.getItem

const userdata = async () => { 
        try {
            return await AsyncStorage.getItem("user_nicename")      
        } catch(error) {
            console.log(error)
        }
    }

    console.log(userdata)
    //returns  { ƒ _callee() {
    //return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.async(function _callee$(_context) {
    //    while (1) {
    //      switch (_context.prev = _context.next) {....

What am I doing wrong here? It seems to be very straightforward.

CodePudding user response:

userdata is an async function. Try this:

console.log(await userdata())

CodePudding user response:

There are a couple of things you are going wrong about this

  • You are logging the function without calling, if you want to see the function evaluated, you have to call it by adding parenthesis for example in your case it would userdata()
  • You are calling an asynchronous function as though it was a synchronous function. Your code was written asynchronously so you need to call it asynchronously as well.
  • As per js convention for naming identifier, turn userdata to userData

For your solution, you will need to call your function, userdata in a promise-based function either async-await or .then or in a callback function. I am suggesting two ways to improve your code.

Method 1: Using .then()

// in home screen
userdata()
    .then((data) => console.log(data))
    .catch((err) => console.log(err));

Method 2: using async-await in your home screen

// home screen
const getUserData = async () => {
   try {
     console.log(await userdata());
   } catch (err) {
     console.log(err);
   }
};

// then call the function
getUserData()

  • Related