3

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?

3
  • 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. Commented Jul 14, 2017 at 18:09
  • 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. Commented Jul 14, 2017 at 18:18
  • 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. Commented Jul 15, 2017 at 19:29

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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?

2 Comments

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
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
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.