reactjs – React js How to get Value within a useEffect and display on defualtValue textfield
I’m trying to get the value of userData which is from a promise in firebase and set that value on my TextField defaulValue when the page loads. But the page loads first before the value can be placed which makes it default:undefined. How can I make my page load with the defaultValue?
import React from 'react'
import { useEffect, useState } from 'react';
import { Grid, TextField} from '@mui/material';
import { useAuth } from '../../contexts/AuthContext';
import { db } from '../../firebase'
import { getDoc, doc } from '@firebase/firestore';
export default function useEditUser() {
const { currentUser } = useAuth();
const [newDisplayName,setDisplayName] = useState("");
const documentId = currentUser.uid
const [userData, setUserData] = useState([]);
useEffect(() =>{
const getUsers = async()=>{
const docRef = doc(db, "user", documentId)
await getDoc(docRef).then(res => {
console.log(res.data().user_fields)
setUserData(res.data().user_fields)
}).catch(err => {
console.log(err)
})
}
getUsers()
},[]);
return (
<form>
<Grid container columnSpacing={1} rowSpacing={1} direction="row" justifyContent="center" alignItems="center" marginBottom={1}>
<Grid item xs={11} sm={8} md={3}>
<TextField defaultValue={console.log("default:" + userData.displayname)} error={newDisplayName===""} defaultValue={userData.displayname} helperText={newDisplayName === "" ? 'Required' : ' '} label="User Display Name*" id="outlined-required" type="text" variant="outlined" onChange={(event) => {setDisplayName(event.target.value)}} sx={{width: '100%'}} />
</Grid>
</Grid>
</form>
)
}
Read more here: Source link
