Search code examples
javascriptreact-nativeasyncstorage

AsyncStorage returns incorrect value


I am very new with react native and might be doing this completely wrong. As suggested on react native documentation, i am using a wrapper for my AsyncStorage. What I am Doing:

  1. I have a class named Storage which serves as wrapper to AsyncStorage code:

    'use strict';
    var React = require('react-native');
    var {
        AsyncStorage
    } =React;
    
    module.exports={
        store(key,value)
        {
            AsyncStorage.setItem(key,value);
        },
        get(key)
        {
            return AsyncStorage.getItem(key);
        },
    }
    
  2. Another class Auth looks for a value with key auth (which is saved already) code:

    'use strict';
    var React = require('react-native');
    
    var Storage=require('./Storage');
    module.exports={
        authKeyExists()
        {
          console.log("IntelliSpend: In Auth::authKeyExists");
          var authKeyPromise=Storage.get('auth');
          var keyExists=true;      
          authKeyPromise.then((authKey)=>{
              console.log('Authkey:'+authKey);
              if(authKey){
                console.log('Authkey exists');
                keyExists= true;
              }
              else {
                console.log('Authkey does not exists');
                keyExists= false;
              }
          }).done();      
          return keyExists;
        }    
    }
    

Ideally as value with key 'auth' exists so it should print "Authkey exists" and should return keyExists as true. But it happens opposite.

On Further diagnosys i found that function authKeyExists returns well before code inside promise objects executes.

I have seen several examples but they all use AsyncStorage on the Screen component itself (i tried that too and failed). I want to abstract out AsyncStorage by using my storage class. Please let me know where i am mistaking.


Solution

  • Your function authKeyExists() will always return true... The functions inside a promise run asynchronously and will actually fire after return keyExists so none of the logic in there that sets keyExists will have any effect. If you want to use the values from the promise you need to use a callback:

    authKeyExists(callback)
    {
      var keyExists;
      var authKeyPromise=Storage.get('auth');
      authKeyPromise.then((authKey)=>{
    
          if(authKey){
            keyExists= true;
          }
          else {
            keyExists= false;
          }
    
          callback(keyExists);
    
      }).done();      
    }    
    

    Which you can then use like this:

    Auth.authKeyExists( (keyExists)=> {
    
       // do something with keyExists
    
    });