[英]Unable to set state after getting document data from Firestore
I am trying to do a User Profile page and after getting the data from Firestore, I'm unable to set the data into the userProfile
state.我正在尝试创建一个用户配置文件页面,在从 Firestore 获取数据后,我无法将数据设置到
userProfile
state 中。
const {userProfile, setUserProfile} = useState(null);
const getUserProfile = async () => {
await firestore().collection("Users")
.doc(user.uid)
.get()
.then(documentSnapshot => {
if (documentSnapshot.exists) {
console.log('User data from Firestore: ', documentSnapshot.data());
setUserProfile(documentSnapshot.data());
}
});
}
useEffect (() => {
if (userProfile == null) {
getUserProfile();
console.log("User Data in userProfile state: ", userProfile);
}
}, [userProfile])
I got this error:我收到此错误:
The console log shows that the userProfile
state is undefined, however, I can retrieve the data from Firestore without any issues as shown in the console log.控制台日志显示
userProfile
state 未定义,但是,我可以从 Firestore 检索数据,没有任何问题,如控制台日志中所示。
const {userProfile, setUserProfile} = useState(null); <----- error is here
const getUserProfile = async () => {
await firestore().collection("Users")
.doc(user.uid)
.get()
.then(documentSnapshot => {
if (documentSnapshot.exists) {
console.log('User data from Firestore: ', documentSnapshot.data());
setUserProfile(documentSnapshot.data());
}
});
}
useEffect (() => {
if (userProfile == null) {
getUserProfile();
console.log("User Data in userProfile state: ", userProfile);
}
}, [userProfile])
Instead of of const {userProfile, setUserProfile} = useState(null);
而不是
const {userProfile, setUserProfile} = useState(null);
replace it with const [userProfile, setUserProfile] = useState(null);
将其替换为
const [userProfile, setUserProfile] = useState(null);
Because u are using curly brackets
in {userProfile,setUserProfile}
因为你在
{userProfile,setUserProfile}
中使用curly brackets
u need to replace it with square brackets
[userProfile,setUserProfile]
你需要用
square brackets
替换它[userProfile,setUserProfile]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.