Paras Watts
Paras Watts

Reputation: 2665

function return value is undefined react native

I am facing problem returning value from a function in react native. It is a global function , not inside any class. I am assigning return value to a var. But value is always undefined.Below is function code snippet.

var userLoggedIn= (function (){
    AsyncStorage.getItem("isLoggedIn").then((login) => {
        var loggedIn = login;
        console.log("Logged In " + loggedIn); // getting correct value
        return loggedIn;
    }).done();
})();

console.log("userLoggedIn" + userLoggedIn); // this is undefined

const IntialScreen = AppNavigator(loggedIn); export default IntialScreen;

Please check what I am doing wrong here. I am new to react native and JavaScript, so I may be doing something wrong or I am not aware about some concept of JavaScript

Upvotes: 0

Views: 3409

Answers (2)

hannad rehman
hannad rehman

Reputation: 4341

you should return a promise when handling async calls. in your case.userLoggedIn is undefined because it gets executed without waiting for the response that AsyncStorage.get item() is returning

var userLoggedIn= (function (){
      return new Promise((resolve, reject) => {
         AsyncStorage.getItem("isLoggedIn").then((login) => {
           var loggedIn = login;
           console.log("Logged In " + loggedIn); // getting correct value
           resolve(loggedIn);
        }).done();
      })

})();

updated based on clarification by OP

export default function(callback){
  userLoggedIn.then((loggedIn)=>{
    //do whatever you want to do with it
   const IntialScreen = AppNavigator(loggedIn);
   callback(IntialScreen);

  })
};

some component

 import InitialScreen from './somefile';
   InitialScreen((loginData)=>{
     //loginData will have what you wanted to export 
   });

Upvotes: 1

shinuq
shinuq

Reputation: 16

var userLoggedIn= false;

(function (){

AsyncStorage.getItem("isLoggedIn").then((login) => {
    var loggedIn = login;
    console.log("Logged In " + loggedIn); // getting correct value
}).done(function() {
    userLoggedIn= loggedIn;
 });

})();

Hope this helps

Upvotes: 0

Related Questions