Search code examples
javascriptreactjsreact-nativeasyncstorage

Promise return undefined AsyncStorage


I have a react-native app where I do some authentication.

I have the following code where I check if the token is not expired and its available.

export const isLogged = () => {

  AsyncStorage.getItem('@token')
    .then( token => {

      if (typeof token !== 'undefined') {

        if (tokenExpired(token)) {

          return false

        }

        return true

      }

      return false

    } )
    .catch( error => {

      return false

    } )

}

But in my code if I do:

let isUserLogged = isLogged()
console.log(isUserLogged) // -> returns undefined, but should return true because the token is there and its not expired.

Does anyone has some idea why its like this, I'm doing something wrong?


Solution

  • You are trying to synchronously get a result that only becomes available asynchronously.

    Change your code like this:

    1. Add return before this call:

      AsyncStorage.getItem('@token')
      

      This will make your isLogged function return something: a promise

    2. Use this promise in your main code:

      isLogged().then( isUserLogged => { 
          console.log(isUserLogged);
      });
      

    The fact that your function isLogged returns a promise (when you return it, that is), is an example of chaining.