React-native-firebase: How to keep a user logged in

Created on 25 Mar 2017  路  5Comments  路  Source: invertase/react-native-firebase

is there a way to keep a user logged in I mean authentication should not lost even after refreshing the app?

Most helpful comment

Yeah this should work as default. You do however need to check for this yourself when the app boots. I do something like so in the "first step component" of my app (cut down a lot):

class App extends React.Component {

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

  componentDidMount() {
    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 />;
  }
}

All 5 comments

Yeah this should work as default. You do however need to check for this yourself when the app boots. I do something like so in the "first step component" of my app (cut down a lot):

class App extends React.Component {

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

  componentDidMount() {
    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 />;
  }
}

Thanks so much @Ehesp! You're amazing!

@Ehesp I have my express server issuing JWT tokens to my react-native app on signin. So what should I do in this case. even if I store JWT token in AsyncStorage, it is going to expire after some time.

When the app boots, you could fire a "ping" request at the server which returns a refreshed token (or checks whether it's expired or not. If it's expired, show them the login page.

Also, each time a request is made to the server also return a refreshed token and keep updating it.

Thanks @Ehesp :)

Was this page helpful?
0 / 5 - 0 ratings