Reputation: 79
import firebase from './firebase';
const auth = firebase.auth();
function display(user) {
if (user) {
window.location = 'home.html';
}
else {
window.location = 'login.html';
}
}
export default function onAuthChange() {
auth.onAuthStateChanged(display);
}
This code causes my page to refresh again and again. How do I fix this? I am using vanilla js.
I tried an altogether different solution that uses auth().currentUser === null
to check and load the correct page but it comes with its own problems in that the page takes time to find out the current state which is initally null on refresh.
Upvotes: 0
Views: 468
Reputation: 3842
The reason is because onAuthStateChanged()
returns a trinary value, not binary. It will return either:
undefined
: The SDK has loaded but hasn't checked user's authentication status yet.
null
: User is definitely unauthenticated.
firebase.auth.User
: User is authenticated.
When you do a simple if (user is truthy) {}
test the user will always appear unauthenticated on first load.
The following changes should fix it:
import firebase from './firebase';
const auth = firebase.auth();
function display(user) {
if (typeof user === "undefined") {
// SDK has loaded but we don't know the user's real status yet
return;
} else if (user === null) {
// User is definitely unauthenticated
window.location = 'login.html';
} else {
// User is authenticated
window.location = 'home.html';
}
}
export default function onAuthChange() {
auth.onAuthStateChanged(display);
}
Upvotes: 0
Reputation: 9151
This is caused by setting window.location
. It basically refreshes your page. This causes the user to be logged out and re-logged in automatically.
If you are using Angular you can solve this with routing, which does not reload the page.
Upvotes: 1