【发布时间】:2020-11-16 10:22:00
【问题描述】:
这是我第一次使用 firestore,我有一个 react 应用程序,我想在其中显示登录用户的用户名。我尝试从使用用户电子邮件查询用户的 firestore 数据库中获取用户名。
firebase.js
export const GetUserName = (email)=>{ //get single doc by email
let name = []; //store the name
//this is where the problem begins
db.collection('users').where("Email", "==" ,email)
.get()
.then(snapShot=>{
snapShot.forEach((snap)=>{
name.push(snap.data().userName); //stores only in array temporarily
console.log(name) //shows correct array
});
})
.catch(err =>{
console.log(err);
})
console.log(name); //shows empty array
return name[0]; //array is empty
}
然后我尝试在我拥有的另一个组件中显示用户名
profilePage.js
import {GetUserName} from '../firebase';
export default function ProfilePage(){
const {user , logout} = useAuth(); //this is access to user.email
return (
<div>
<h1>Hi {getUsername(user.email)} </h1>
<Button onClick={handleLogout} color = "primary" variant = "outlined">Log out</Button>
</div>
);
}
但是没有用户名我只会得到“hi”
【问题讨论】:
-
不要使用
const name = [ ]尝试使用state variablebyuseState
标签: reactjs firebase google-cloud-firestore