I am not able to access UID in firebase on other HTML pages than login page

Viewed 36
firebase.initializeApp(firebaseConfig);  

  const auth = firebase.auth();

 function signUp(){

          var email = document.getElementById("emailsu");
          var password = document.getElementById("passwordsu");

          const promise = auth.createUserWithEmailAndPassword(email.value, password.value);
          promise.catch(e => alert(e.message));
          alert("Signed Up");
  }
  

  function signIn(){

    var email = document.getElementById("email");
    var password = document.getElementById("password");

    const promise = auth.signInWithEmailAndPassword(email.value, password.value);
    promise.catch(e => alert(e.message));

}

 

    auth.onAuthStateChanged(function(user){
      if(user){
        window.location.assign("Landing Page"); 
      }else{
            //no user is signed in
      }
    });


function signOut(){
  auth.signOut();
  alert("Signed Out");
  window.location.replace("index.html");
}

This is my authentication JavaScript And when I tried to link this file using script tag to access UID pages other than login page... It starts to reload recursively... I want to Access UIDs and save them in database as DOCUMENT name so I can fetch the data using UID of the user

the folder contains 6 Different HTML pages but it only authenticates the login page

1 Answers

You just need to do it after the promise of auth.createUserWithEmailAndPassword() has been fulfilled, which will return you a UserCredentials object which contains the uid you want, and then you can create a document in Firestore with that, like this:

const promise = auth.createUserWithEmailAndPassword(email.value, password.value)
                    .then(function(userCredential) {
                        firestore.collection('users').doc(userCredential.user.uid).set({
                            email: email.value
                        })
                    })

With that approach the uid of that document will be the same as the uid of the auth credentials, however, because you will be using the same value you will have to set the document with some other value since no document can be created empty. Since email was available and it is a user information that can be added to the document I used that variable and you can add more information later in your app's execution.

Also make sure to initialize the Firestore as well with:

const firestore = firebase.firestore();
Related