Pro
Pro

Reputation: 485

why is my firebase authentication display name not getting updated properly with react js?

I am trying to build firebase authentication for my react app..After I sign in I am trying to update the displayName and then redirect..On the redirected page I am trying to greet the user by fetching the display name saved while signing up with firebase..This page works properly immediately after I redirect but if I reload this page then it is not able to show the displayName and throws this error:

TypeError: Cannot read property 'displayName' of null

This is the function which gets triggered when signup button is clicked..

 const signup = async () => {
        try{
            await firebaseApp.auth().createUserWithEmailAndPassword(email, password)
            await firebaseApp.auth().currentUser.updateProfile({displayName:username})
            console.log(firebaseApp.auth().currentUser)
            if (!firebaseApp.auth().currentUser){
                setLoading(true)
            }
            history.push('/home')
        }catch (error){
            alert(error.message)
        }
    } 

This is the JSX of the page which is being redirected to by signup page:

<div className="greetings">
  Good Evening {firebaseApp.auth().currentUser.displayName}
</div>

Why is this issue happening and how to resolve it?

Upvotes: 0

Views: 1320

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

firebaseApp.auth().currentUser is always null when a page first loads. It won't contain a User object until some time later, after the SDK is able to load and verify the auth token for that user. Instead of using currentUser, you should set up an auth state observer as shown in the documentation. This observer will get invoked as soon as the User object is known.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    // ...
  } else {
    // User is signed out.
    // ...
  }
});

You can use the results of this observer function to know when the user is signed in or signed out over time. To learn more about how it works, read this blog post.

Upvotes: 1

Related Questions