Skip to content Skip to sidebar Skip to footer

Firebase OnAuthStateChanged() Triggering Before Retrieving Name From Signup Form?

I'm creating a dashboard using vanilla HTML, CSS and JS, with Firebase as my backend. In my signup.html page, I have a form that allows users to input their name along with their e

Solution 1:

It seems like your onAuthStateChanged listener is being triggered before the write to the database has completed. This is the expected behavior for the API, but not what you want here.

Since you do want to use the onAuthStateChanged listener to navigate on page reload, the best I can think off is to turn off the listener when the user clicks the sign up button:

// 👇 store the unsubscribe function in a variable
var unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
        window.location.replace('dashboard.html')
    } else {
        return
    }
});

document.querySelector('#signup_btn').addEventListener("click", (e) => {
    e.preventDefault();

    unsubscribe(); // 👈 turn off auth state listener

    var user_email = document.getElementById('user_email').value;
    var user_pass = document.getElementById('user_pass').value;
    var user_name = document.getElementById('user_name').value;

    // Sign Up
    firebase.auth().createUserWithEmailAndPassword(user_email, user_pass)
        // Success
        .then((userCredentials) => {
            return userCredentials.user.updateProfile({ // 👈 add a return
                displayName: user_name
            })
        })
        .then(() => {
            window.location.replace('dashboard.html') // 👈 explicitly navigate here
        })

Solution 2:

As mentioned in the documentation,

onAuthStateChanged adds an observer for changes to the user's sign-in state.

When the user is logged in, it redirects your user to /dashboard before the updateProfile is resolved resulting in termination of that request.

enter image description here

I don't think you'll need an auth state listener on login page so try refactoring the code like this:

window.onload = function () {
  if (firebase.auth().currentUser) window.location.replace("dashboard.html")

  // Else stay on this page
  // button click events here
}

Post a Comment for "Firebase OnAuthStateChanged() Triggering Before Retrieving Name From Signup Form?"