When mounting a component, I'd like to render either a log in screen or the app, depending on wether the user in logged in. However, each time I refresh, the user is logged out. How would I keep them logged in?
firebase.initializeApp(config); //init the firebase app...
class App extends Component {//this component renders when the page loads
constructor(props){
super(props);
this.state = {user: firebase.auth().currentUser};//current user
}
render(){
if (this.state.user) {//if you are logged in
return (
<Application/>
);
} else {//if you are not logged in
return (
<Authentication/>
);
}
}
}
This is the method I'm using to log in the user (which works fine):
let email = "some";
let password = "thing";
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, password);
The underlying ID token that authenticates refreshes every hour. So, after an account is deleted, the client will be authenticated for up to one hour. Only until it tries to refresh the ID token will the client become unauthenticated.
Firebase Authentication sign-ins are permanent There is no specific time-out on the authentication of a user, so you should not ask them to re-authenticate based on the expired time.
The user's token is automatically persisted to local storage, and is read when the page is loaded. This means that the user should automatically be authenticated again when you reload the page.
The most likely problem is that your code doesn't detect this authentication, since your App
constructor runs before Firebase has reloaded and validated the user credentials. To fix this, you'll want to listen for the (asynchronous) onAuthStateChanged()
event, instead of getting the value synchronously.
constructor(props){
super(props);
firebase.auth().onAuthStateChanged(function(user) {
this.setState({ user: user });
});
}
I had the same issue with Firebase in React. Even though Firebase has an internal persistence mechanisms, you may experience a flicker/glitch when reloading the browser page, because the onAuthStateChanged
listener where you receive the authenticated user takes a couple of seconds. That's why I use the local storage to set/reset it in the onAuthStateChanged listener. Something like the following:
firebase.auth.onAuthStateChanged(authUser => {
authUser
? localStorage.setItem('authUser', JSON.stringify(authUser))
: localStorage.removeItem('authUser')
});
Then it can be retrieved in the constructor of a React component when the application starts:
constructor(props) {
super(props);
this.state = {
authUser: JSON.parse(localStorage.getItem('authUser')),
};
}
You can read more about it over here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With