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

左心房为你撑大大i 提交于 2019-12-10 15:47:07

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/58406027/check-if-user-is-logged-in-or-not-using-firebase-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!