Milos
Milos

Reputation: 1253

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

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?

Upvotes: 3

Views: 20956

Answers (3)

devDevDev
devDevDev

Reputation: 29

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;

Upvotes: 1

Namwanza Ronald
Namwanza Ronald

Reputation: 376

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.

Upvotes: 3

Umang Galaiya
Umang Galaiya

Reputation: 702

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?

Upvotes: 1

Related Questions