Amir
Amir

Reputation: 513

Redirect a logged in user using firebase in react-native

What I want is that if the user is already signed in, the app should skip the log in page for him and display the main page. I tried the below code but it doesn't work. How to overcome this issue ?

componentWillMount() {
   let user = firebase.auth().currentUser;
   if (user != null) {
      this.props.navigation.navigate('Drawer'); 
   }  
   this.unsubscribe = firebase.auth().onAuthStateChanged(user => {
    if (user) {
     this.props.navigation.navigate('Drawer');
   }  
  });  
}

Upvotes: 0

Views: 686

Answers (1)

Gastón Saillén
Gastón Saillén

Reputation: 13129

Take a look at this hint, it should solve your problem

class App extends React.Component {

      constructor() {
        super();
        this.state = {
          loading: true,
          authenticated: false,
        };
      }

      componentWillMount() {
        firebase.auth().onAuthStateChanged((user) => {
          if (user) {
            this.setState({ loading: false, authenticated: true });
          } else {
            this.setState({ loading: false, authenticated: false });
          }
        });
      }

      render() {
        if (this.state.loading) return null; // Render loading/splash screen etc

        if (!this.state.authenticated) {
          return <Login />;
        }

        return <Home />;
      }
    }

Upvotes: 1

Related Questions