[英]React Firestore how to get document field on load
I'm new to Firestore and I'm trying to get the value of displayname
in a document field when the page loads so that I can place the value as a defualtValue
in a TextField
.我是 Firestore 的新手,我试图在页面加载时在文档字段中获取
displayname
的值,以便我可以将值作为defualtValue
值放在TextField
中。
import React from 'react'
import { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { db } from '../firebase'
import { getDoc, doc} from "firebase/firestore";
import { TextField } from '@mui/material';
export default function EditUser() {导出默认 function EditUser() {
const { currentUser } = useAuth();
const [userData, setUserData] = useState([]);
useEffect(() =>{
const getUsers = async()=>{
const documentId = currentUser.uid
const docRef = await doc(db, "user", documentId)
const usersCollectionRef = await getDoc(docRef)
setUserData(usersCollectionRef.get("user_fields"))
console.log(userData)
}
getUsers()
}, []);
return (
<form>
<TextField defaultValue={userData.displayname}></TextField>
</form>
)
} }
but on load console.log(userData.displayname)
displays undefined
or an empty array
但在加载时
console.log(userData.displayname)
显示undefined
或空array
Edit: I tried making it an event by adding it in an onClick
to debug it's always the first time the data doesn't show once I click it a 2-3 times it shows the data (not sure if this helps)编辑:我尝试通过将其添加到
onClick
中来使其成为一个事件来调试它总是第一次当我单击它时数据不显示 2-3 次它显示数据(不确定这是否有帮助)
The Firebase document you linked has collection "user_field s " and not "user_field".您链接的 Firebase 文档具有集合“user_field s ”而不是“user_field”。 So if you change
所以如果你改变
setUserData(usersCollectionRef.get("user_field"))
to至
setUserData(usersCollectionRef.get("user_fields"))
that should fix the problem那应该可以解决问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.