Search code examples
authenticationreact-nativetokenes6-promiseasyncstorage

Unable to return token from AsyncStorage in React Native


I am using React Native's AsyncStorage to store an authorization token, which will be returned when needed to use for new http requests. While I can successfully store it and console log it, I am having some trouble returning the value. I want to call it in another window, in the fashion of

 var x= LocalDb.getAcessToken();
 console.log(x);

However it won,t work.

 LocalDb.getAccessToken();

This on the other hand, works when getAcessToken() has console.log in it

exports.storeToken=function(token){
  AsyncStorage.setItem('access_token', token);
  }

^^^^This function successfully saves the token

exports.getAccessToken=function(){
   AsyncStorage.getItem('access_token')
   .then((value) => {
       if(value) {
        console.log(value);
    **//I want to return the value here, to use in another function**
      }
    })
  .done();
}

I can not return the value when I use the return(value) . How can I return a value from the promise?


Solution

  • You need to return the getAccessToken function with the promise call. I would also return the promise with the value... like this.

    exports.getAccessToken=function(){
     return AsyncStorage.getItem('access_token')
     .then((value) => {
         if(value) {
          console.log(value);
          return value;
        }
       })
    }