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
.
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() {
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
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)
The Firebase document you linked has collection "user_field s " and not "user_field". So if you change
setUserData(usersCollectionRef.get("user_field"))
to
setUserData(usersCollectionRef.get("user_fields"))
that should fix the problem
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.