[英]Check if user is logged in or not using firebase in react
I do have a react
with firebase
project.我确实对firebase
项目有react
。 So I successfully able to login the user via firebase
authentication.所以我能够通过firebase
身份验证成功登录用户。 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()
.我想,我可以像 laravel 的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.我的signin.js
页面。
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.我想要访问用户变量的dashboard.js
页面。
componentDidMount() {
if(localStorage.getItem('uid')){
//alert("welcome"+localStorage.getItem('uid'));
this.setState({user : JSON.parse(localStorage.getItem('uid'))})
console.log("this : "+localStorage.getItem('uid'))
}
}
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.您可以在firebase.auth()
回调上使用currentUser
方法来获取用户详细信息。 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如果您使用前端 firebase package 登录,那么这没有问题,无论您是在同一页面还是在任何其他页面上调用它
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.嗨,我很确定为什么会发生这种情况,因为处理登录到您的 firebase 帐户的 firebase 自动登录功能速度不快,根据我的经验,填写身份验证 state 需要 0.5-2 秒,到您的时间页面检查 auth.currentUser 它没有得到任何因为登录尚未完成。
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在您的仪表板页面上,在安装时有一个 onAuthStateChange function 并且不要担心它只在 auth state 更改上工作,它会在每次安装您的仪表板时运行,然后用户 object 来自
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.