2
votes

I have been having trouble getting the display name out of Firebase. below is the Sign Up process coding

 const promise = auth.createUserWithEmailAndPassword(email, pass)
 .then(
    (user)=>{
   // here you can use either the returned user object or       
 firebase.auth().currentUser. I will use the returned user object
      if(user){
        user.updateProfile({
           displayName: textUsername.val(),
        //    photoURL: // some photo url
        })
      }
  })
  .then( function() {
      console.log('User Name Set!')
  })
  .catch(function() {
    console.log('error')
  });
 promise.catch(e => console.log(e.message));

 })

 firebase.auth().onAuthStateChanged(firebaseUser => {
  if(firebaseUser) {
      console.log(firebaseUser)
  } else {
    console.log('not logged in');
  }
 })

the console.log shows 'user name set!' and the console.log(firebaseUser) shows that the displayName is set in the database of the currentUser, and the name is what i expected. However,

console.log(firebase.auth().currentUser) 

gives null, and

if (user != null) {
    console.log(user.displayName);
}

this also returns as null.

I have been looking for ways to get the data of the firebase dataset but I cannot manage to do that.

it will be great if anyone can give me any advice about it.

Thank you.

2

2 Answers

0
votes

firebase.auth().currentUser.displayName returns the OAuth provider's display name. However, firebase.auth().currentUser resolves asynchronously and is empty/null for a moment on page load. If you put the console.log(firebase.auth().currentUser.displayName) inside the .onAuthStateChanged you'll see that.

0
votes

I ended up using recursion to solve this. I wish there was a more elegant way but this was the only thing that worked for me. Please share if you have solved this with a different solution!!

I needed this for creating new users. When someone signed in it never seems to return null.

The setTimeout() slows the recursion down by .5 seconds so that you don't get an error by calling the function too many times. You can speed it up or slow it down by adjusting the milliseconds.

Working code:

auth.onAuthStateChanged(user => {
    if (user) {
      // Everything inside here happens if user is signed in
      console.log(user)

      // Greet the user with a message and make it personal by using their display name
     injectDisplayName = () => {
          if(firebase.auth().currentUser.displayName === null){
              console.log('happens');
              setTimeout(() => {
                injectDisplayName()
            }, 500)
          } else {
              document.getElementById('display-name-header').textContent = `Hello, ${firebase.auth().currentUser.displayName}`
          } 
      }
      injectDisplayName()

    } else {
      // Everything inside here happens if user is not signed in
    }
  })