Search code examples
react-nativereact-navigationiphone-x

React Native code behave differently on iPhone X simulator


I am using react navigation 2 with React native to build an Authentication flow (following this tutorial).

The application works fine when I run it in the iPhone 6s simulator. The app directs me to the Welcome screen as no userToken is found in AsyncStorage.

My code is the following:

AuthLoadingScreen.js

import React from 'react'
import {
  StyleSheet,
  View,
  ActivityIndicator,
  AsyncStorage,
} from 'react-native'


export default class AuthLoadingScreen extends React.Component {
  constructor() {
    super()
    this.loadApp()
  }
  // Remember logged in user
  loadApp = async () => {
    const userToken = await AsyncStorage.getItem('userToken')
    this.props.navigation.navigate(userToken ? 'App' : 'Auth')
  }
  render() {
    return (
      <View style={styles.container}>
        <ActivityIndicator size="large" color="#fff" />
      </View>     
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#aa73b7',
    alignItems: 'center',
    justifyContent: 'center',
  },
})

WelcomeScreen.js

import React from 'react'
import {
  StyleSheet,
  View,
  Text,
} from 'react-native'


export default class WelcomeScreen extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>WelcomeScreen</Text>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#aa73b7',
    alignItems: 'center',
    justifyContent: 'center',
  },
})

App.js

import { createSwitchNavigator, createStackNavigator } from 'react-navigation'

import WelcomeScreen from './src/components/screens/WelcomeScreen'
import AuthLoadingScreen from './src/components/screens/AuthLoadingScreen'


const AuthStackNavigator = createStackNavigator({
  Welcome: WelcomeScreen,
})

export default createSwitchNavigator({
  Authloading: AuthLoadingScreen,
  Auth: AuthStackNavigator
}) 

However, when I run the following app in the iPhone X simulator, it keeps showing the activity indicator instead of directing me to the welcome screen (the expected behavior).

Can anyone explain why is this happening?


Solution

  • call this.loadApp() in componentDidMount instead of constructor it should work.