Search code examples
react-nativenavigationreact-native-router-flux

components get render even routed out on componentWillMount method?


class LoginScreen extends Component {
  componentWillMount() {
    const { currentUser } = firebase.auth();
    console.log(currentUser);
    if (currentUser) {
      Actions.mainScreen();
    }
  }

  render(){...}
}

Basically the idea very simple, once user comes to LoginScreen, it checks if the user existed, if yes, instead of render this component, redirect to another component instead.

The problem with the above code is that, LoginScreen still gets to render for 1 to 2 seconds before render mainScreen. Wondering if this is the way to handle such routing conditionally in React-Native-Router-Flux?


Solution

  • To solve this problem. declare a state

    state = {
       isChecking: true
    }
    

    in your componentWillMount

    componentWillMount() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        Actions.mainScreen();
      } else {
        this.setState({ isChecking: false });
      }
    });
    } 
    

    or better still with the async/await syntax

    async componentWillMount() {
    let user = await firebase.auth().onAuthStateChanged;
    user ? Actions.mainScreen() : this.setState({ isChecking: false });
    

    In your render method first, check when you are still checking or not. If so just render an activityIndicator. At the very very top of your render method check whether you are still checking or not.

    render() {
    if (this.state.isChecking) {
      return (
        <View
          style={{ justifyContent: "center", alignItems: "center", flex:1 }}
        >
          <ActivityIndicator size={"large"} />
        </View>
      );
       // rest of your loginScreen components
    }