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.
JavaScript
x
21
21
1
const {userProfile, setUserProfile} = useState(null);
2
3
const getUserProfile = async () => {
4
await firestore().collection("Users")
5
.doc(user.uid)
6
.get()
7
.then(documentSnapshot => {
8
if (documentSnapshot.exists) {
9
console.log('User data from Firestore: ', documentSnapshot.data());
10
setUserProfile(documentSnapshot.data());
11
}
12
});
13
}
14
15
useEffect (() => {
16
if (userProfile == null) {
17
getUserProfile();
18
console.log("User Data in userProfile state: ", userProfile);
19
}
20
}, [userProfile])
21
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.
Advertisement
Answer
JavaScript
1
21
21
1
const {userProfile, setUserProfile} = useState(null); <----- error is here
2
3
const getUserProfile = async () => {
4
await firestore().collection("Users")
5
.doc(user.uid)
6
.get()
7
.then(documentSnapshot => {
8
if (documentSnapshot.exists) {
9
console.log('User data from Firestore: ', documentSnapshot.data());
10
setUserProfile(documentSnapshot.data());
11
}
12
});
13
}
14
15
useEffect (() => {
16
if (userProfile == null) {
17
getUserProfile();
18
console.log("User Data in userProfile state: ", userProfile);
19
}
20
}, [userProfile])
21
Instead of of const {userProfile, setUserProfile} = useState(null);
replace it with const [userProfile, setUserProfile] = useState(null);
Because u are using
curly brackets
in {userProfile,setUserProfile}
u need to replace it with
square brackets
[userProfile,setUserProfile]