Wave Metric
Wave Metric

Reputation: 129

Have I called the onAuthStateChanged function incorrectly?

githubLogin.addEventListener('click', () => {
    var provider = new firebase.auth.GithubAuthProvider();

    firebase.auth().signInWithPopup(provider).then(function(result) {
        var user = result.user;
        console.log(user);
        firebase.auth().onAuthStateChanged(function(user) {
            if (user) {
                window.location = "pages/welcome.html";
            }});
    }).catch(function(error) {
        console.log(error);
    });

});

So the problem is that, when I redirect the user to welcome and I see that there's no user logged in on that page. I know I've got to use the onAuthStateChanged() function but I've got it wrong so far. Can I know how this can be done? and also I've got something similar for google login, is that affecting the function?

Upvotes: 0

Views: 410

Answers (1)

bojeil
bojeil

Reputation: 30838

You should determine the Auth state before you show the button. If onAuthStateChanged listener initially triggers with a null user, you display the login screen.

Also when you call signInWithPopup, you don't need to add the state change listener. You can just do:

firebase.auth().signInWithPopup(provider).then(function(result) {
  // User logged in, you can get currentUser from onAuthStateChanged
  // listener on welcome page.
  window.location.assign("pages/welcome.html");
}).catch(function(error) {
  // Handle error.
});

Upvotes: 1

Related Questions