Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get just the first name when a user logs in using social media with firebase?

Here is the code that I am using to get the details of the user when they log in using google, facebook or twitter.

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var displayName = user.displayName;
        var email = user.email;
        var emailVerified = user.emailVerified;
        var photoURL = user.photoURL;
        var uid = user.uid;
        var phoneNumber = user.phoneNumber;
        var providerData = user.providerData;
        user.getToken().then(function(accessToken) {

            console.debug('user', user);

            document.getElementById('name').textContent = displayName;
            document.getElementById("avatar").src = photoURL;


        });

    } else {
        console.log('not logged in');

    }

});

Then in the html by writing <p id="name"></p> the entire name of the user is displayed.

How do I display just the first name of the user?

like image 314
Steve Doson Avatar asked Jan 02 '26 01:01

Steve Doson


2 Answers

You can do it like this;

document.getElementById('name').textContent = (displayName.split(' '))[0];
like image 138
Wasif Ali Avatar answered Jan 03 '26 14:01

Wasif Ali


First and last name are available from most social providers just after you log in, but you will need to save them to your database as Firebase does not. What each provider calls first and last name varies, though.

Documentation at https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signinwithpopup

firebase.auth
  .signInWithPopup(new firebase.auth.GoogleAuthProvider())
  .then((user) => {
    const firstName = user.additionalUserInfo.profile.given_name;
    const lastName = user.additionalUserInfo.profile.family_name;
  });

firebase.auth
  .signInWithPopup(new firebase.auth.OAuthProvider('microsoft.com'))
  .then((user) => {
    const firstName = user.additionalUserInfo.profile.givenName;
    const lastName = user.additionalUserInfo.profile.surname;
  });
like image 42
waternova Avatar answered Jan 03 '26 15:01

waternova



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!