How can i get access to the current user inside of react from firebase?

11,007

Solution 1

This will display the current user's email.

    import React from 'react';
    import firebase from "firebase/app";
    import "firebase/auth";
        
    class Profile extends React.Component {
       render () {
          let user = firebase.auth().currentUser;
             return (
                 <p> I'm the current user: {user.email} </p>
             );
       }
    }
        
   export default Profile;

However, if you want to display the name of the current user, you will have to use other methods of authentication with firebase like; Google sign-in, Facebook Login, twitter, phone number etc, but not with Password Authentication.

Solution 2

Can you try moving

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        console.log('This is the user: ', user)
    } else {
        // No user is signed in.
        console.log('There is no logged in user');
    }
});

from render to the end of constructor instead?

Solution 3

I would I like to differ from @Ronald Namwanza as he says that you cannot get the users name when using email and password authentication but you actaully can You can get a number props of the user not just name instead all the props are available here: https://firebase.google.com/docs/reference/js/firebase.User

You can put in a displayName for the user when they sign up. The example:

function signUp() {
  auth.createUserWithEmailAndPassword(email, password).then((authUser) => {
    authUser.updateProfile({
      displayName: thisCanBeAnyVariableOrInputYouTookFromTheUser,
})
})
}

This way you can give the user a name and to get the name:

const user = firebase.auth().currentUser;

// Then get the username by using:
const name = user.displayName;
Share:
11,007
Milos
Author by

Milos

I'm a full-stack developer currently based in Cleveland, OH looking for work. I've built and deployed applications in NodeJS, React, AWS, Heroku, MySQL, PostgreSQL, and more. I'm very willing to relocate if needed.

Updated on June 15, 2022

Comments

  • Milos
    Milos almost 2 years

    I may be a bit confused on what firebase is trying to do here. I can get a user to sign into my site using the existing firebase code I have in react, but when I try to get any sort of access to the username of that user (so i can print it out on the screen), I don't get anything.

    The filestructure of my react app is index.jsx which loads Login.jsx. Login.jsx looks like this:

    import React from 'react';
    import axios from 'axios';
    import * as firebase from 'firebase';
    
    
    
    class Login extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {email: '', password: ''};
        this.engageLogin = this.engageLogin.bind(this);
        var config = {
          apiKey: "-------------------",
          authDomain: "--------.firebaseapp.com",
          databaseURL: "https://------.firebaseio.com",
          projectId: "-------",
          storageBucket: "-------.appspot.com",
          messagingSenderId: "------------"
        };
        firebase.initializeApp(config);
      }
    
    
      engageLogin (event) {
        var provider = new firebase.auth.GoogleAuthProvider();
        firebase.auth().signInWithPopup(provider).then(function(result) {
        // This gives you a Google Access Token.
        var token = result.credential.accessToken;
        // The signed-in user info.
        var user = result.user;
        });
        event.preventDefault();
      }
    
      render() {
        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            console.log('This is the user: ', user)
          } else {
            // No user is signed in.
            console.log('There is no logged in user');
          }
        });
        return (
          <div>
            <div className="container">
              <h2 className="title"> Stream Labs </h2>
              <form onSubmit={this.engageLogin}>
                <div className="form-group row">
                    <div type="submit" className="g-signin2">Sign in</div>
                </div>
              </form>
            </div>
          </div>
        );
      }
    }
    
    export default Login;

    From what I understand, that firebase.auth().onAuthStateChanged is supposed to fire off and console.log whenever a user logs in, but I only ever get the 'there is no logged in user' message. Can anyone point me in the right direction here?

    • jered
      jered almost 7 years
      Are you sure that you have successfully logged in using the GoogleAuthProvider? Maybe an incorrect username and/or password is triggering the callback but there is no valid user logged in.
    • Milos
      Milos almost 7 years
      The only indication i seem to get is that there are no errors and the google button changes from sign in to "signed in" once the google pop up auth completes.
    • bojeil
      bojeil almost 7 years
      Are you using Google sign-in library GApi which provides a sign-in button? Or are you actually using GoogleAuthProvider? and signing in with popup? Try logging the result of signInWithPopup to confirm it is successful.
  • Andrew Irwin
    Andrew Irwin over 5 years
    one thing that catches me out a lot is functions that are synchronous and async. if you are getting undefined/null values it may be because the values are not ready yet because you are calling an async function in a place that is synchronous
  • Andrew Irwin
    Andrew Irwin over 5 years
    Also I think its a good idea to have firebase.auth().onAuthStateChanged in onComponentDidMount if you want to get the current user when the page has loaded