[英]how to save session using firebase?
我已经在我的应用程序中使用
firebase.auth().SignInWithEmailAndPassword (email, password)
而且我需要当用户访问该站点时,他的个人资料将在登录时同步,甚至页面将被重新加载或关闭并再次打开
class App extends Component {
constructor(props) {
super(props);
this.state = {
email: " ",
password: " ",
hasAccount: false,
}
}
componentDidMount() {
const db = firebase.database();
console.log(db)
}
handleChange = ({ target: { value, id } }) => {
this.setState({ [id] : value })
}
createAccount = () => {
const { email, password } = this.state;
firebase.auth().signInWithEmailAndPassword( email, password)
.then(Response => {
console.log(Response)
this.setState({ hasAccount: true })
})
.catch(error => console.log(error))
const auth = firebase.app().auth();
auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
}
在许多环境中 Firebase 已经保留了用户的身份验证凭据,您不需要使用auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
显式启用它。
但是要在应用程序重新启动/页面重新加载时获取恢复的身份验证 state,您需要使用onAuthStateChanged
处理程序,如获取当前用户的文档中的第一个片段所示:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
this.setState({ hasAccount: true })
} else {
// No user is signed in.
}
});
您通常会将此代码放在组件的构造函数中,以便它立即开始监视身份验证 state。
componentDidMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in.
this.setState({ hasAccount: true })
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.