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

Viewed 1250

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?

2 Answers

You can do it like this;

document.getElementById('name').textContent = (displayName.split(' '))[0];

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;
  });

Related