我如何显示displayName从我的用户文档在firestore?



我可以使用auth登录并检索数据,用户/uid文档显示在firestore控制台

{displayName: "John"}

从这个路径路径:"appname/users/uid">

但是当我使用

<div>{auth.currentUser?.displayName}</div> or console.log(auth.currentUser?.displayName)

displayName: null

看来我的{auth}只显示email, uid,其他什么都没有,尽管在firestore中我可以看到我之前为这个用户保存的DisplayName和photoUrl/uid

如何显示用户/uid对象,而不依赖于auth对象的用户详细信息?

组件:

const fetchData = async () => {
const userId = auth.currentUser?.uid;
const docRef = collection(db, "users", userId as string, "pred");
const preds = await getDocs(docRef);
const predList = preds.docs.map((doc) => doc.data());
console.log(predList);
const q = doc(db, `users/${userId}`);
console.log(q); //doesnt' work
console.log(auth) //only shows email, displayName is null;
};

如果我登录与谷歌,我可以看到的displayName和照片,如果我登录与hotmail帐户我不能看到这些,但在firestore我有一个displayName和photoUrl保存在appName/user/uid/

的用户firebase-auth.ts:

const signInWithGoogle = async () => {
try {
const res = await signInWithPopup(auth, googleProvider);
const user = res.user;
const q = query(collection(db, "users"), where("uid", "==", user.uid));
const docs = await getDocs(q);
if (docs.docs.length === 0) {
await addDoc(collection(db, "users"), {
uid: user.uid,
name: user.displayName,
authProvider: "google",
email: user.email,
});
}
} catch (err: any) {
console.error(err);
alert(err.message);
}
};
const logInWithEmailAndPassword = async (email: any, password: any) => {
try {
await signInWithEmailAndPassword(auth, email, password);
} catch (err: any) {
console.error(logInWithEmailAndPassword, err);
alert("logInWithEmailAndPassword" + err.message);
}
};

所以getDocs, getDoc, doc和collection是有区别的。我需要在getDoc中使用doc,因为我是在获取一个doc,而不是查询一个集合。

import { collection, doc, getDoc, getDocs } from "firebase/firestore";
const q = doc(db, "users", userId as string);
const x = await getDoc(q);
const y = x.data();

最新更新