I am new to React Native and only started learning it few weeks ago. 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.
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 am able to retrieve the data from Firestore without any issues as shown in the console log.
I have been trying to solve it for a long time now and still unable to solve it. Any help will be greatly appreciated!
CodePudding user response:
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);
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]