2

I am using react-native where my first screen is Welcome screen and I want to set dashboard on my first screen when the user is login.

Here is my code:

componentWillMount(){
    var self = this;
    AsyncStorage.getItem(AppStrings.contracts.IS_LOGGED_IN).then((json) =>{
        try{
            var userDetail =   JSON.parse(json);
            if(userDetail.isLoggedIn != undefined && userDetail.isLoggedIn == true){
                Actions.dashboard();
            }
        }catch(e){
        }
    })
}

I set this code on the Welcome screen and its working fine in IOS. But in android issue is it shows the Welcome screen for 5 to 10 seconds before going to dashboard screen when the user is login.

Here I am using react-native-router-flux for the navigation bar.

Sandeep Mishra
  • 650
  • 2
  • 9
  • 20

1 Answers1

1

Because AsyncStorage.getItem() is asynchronous, your render() function is being called BEFORE it has been fulfilled.

So the flow of your application is:

  1. Call componentWillMount()
  2. AsyncStorage.getItem()
  3. render() - This is where you see your Welcome Screen for 5-10 seconds
  4. AsyncStorage has been fulfilled - .then() and then the User gets redirected to the dashboard.

I would set an isLoaded flag in your state:

constructor() {
  super();
  this.state = {
    isLoaded: false,
  }
}

Then inside of your componentWillMount() function, set the value to true once AsyncStorage has fulfilled its Promise.

try {
  var userDetail =   JSON.parse(json);
  if(userDetail.isLoggedIn != undefined && userDetail.isLoggedIn == true){
    Actions.dashboard();
  }
  this.setState({ isLoaded: true });
}

And finally, I would add some sort of loading indicator inside of render() to show the User that your application is still performing some logic.

render() { if(this.state.isLoading) { return <Text>I am loading</Text> } else { return ... } }

Dan
  • 8,041
  • 8
  • 41
  • 72