farooq
farooq

Reputation: 1673

Check if user is logged in or not using firebase in react

I do have a react with firebase project. So I successfully able to login the user via firebase authentication. What I want to do is to set the user details in all pages. I thought, I can able to access the user variables in react everywhere like laravel's Auth::user() . But I tried in so many ways to achieve that. But I couldn't able to get the user details in another page. Is there any way to get the user details in another page ?

My signin.js page .

  handleSubmit = (e) => {
    e.preventDefault()
    firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then((user) => {
      alert("login success")
      console.log(user.user)
      this.setState({uid:user.user.uid})
      localStorage.setItem('uid',JSON.stringify(user.user))
      window.location.assign('/')
      }).catch(function(error) {
            console.log(error.code)
            alert(error.message)
        })
      }

My dashboard.js page where I want to access user variables .

  componentDidMount() {
    if(localStorage.getItem('uid')){
      //alert("welcome"+localStorage.getItem('uid'));
      this.setState({user : JSON.parse(localStorage.getItem('uid'))})
      console.log("this : "+localStorage.getItem('uid'))
    }
  }

Upvotes: 7

Views: 11847

Answers (2)

Abhay Rohit
Abhay Rohit

Reputation: 55

Hi I'm pretty sure why this is happening as firebase autologin functionality which handles logging you in to your firebase account is not fast, from my experience it takes anywhere from 0.5-2 seconds to fill in the auth state, and by the time your page checks auth.currentUser it doesn't get any as the login is not complete yet.

SOLUTION

on your dashboard page, have an onAuthStateChange function at mount and don't worry about it working only on auth state change, it would run everytime your dashboard is mounted and then the user object from that

Upvotes: 1

HexaCrop
HexaCrop

Reputation: 4263

var user = firebase.auth().currentUser;
var name, email, photoUrl, uid, emailVerified;

if (user != null) {
  name = user.displayName;
  email = user.email;
  photoUrl = user.photoURL;
  emailVerified = user.emailVerified;
  uid = user.uid;  // The user's ID, unique to the Firebase project. Do NOT use
                   // this value to authenticate with your backend server, if
                   // you have one. Use User.getToken() instead.
}

you can use currentUser method on firebase.auth() callback to fetch user details. If you are signing in using frontend firebase package then this is no issue, whether you call this on the same page or any other page

Upvotes: 5

Related Questions