I wrote the following code to get the details of the currently logged-in user from Firebase's Firestore in ReactNative, but it didn't work and I couldn't get the <Text>{currentUserInfo.username}</Text> or No value is displayed in currentUserInfo
When the following code is executed, we would originally like the console to output 1,2,3 in that order, but currently it is executed in the order 2,3,1 as shown in the image below.
I think the reason why there are no values in <Text>{currentUserInfo.username}</Text> or currentUserInfo is because the order of execution is wrong and there are no values in let userdata, but how can I improve this? What should I do to improve this?
I would appreciate it if you could tell me more about it.
import { View, Text } from "react-native";
import React, { useState, useEffect } from "react";
import { db } from "../firebase";
import { collection, query, where, getDocs } from "firebase/firestore";
const test = () => {
const [currentUserInfo, setCurrentUserInfo] = useState();
const auth = getAuth();
useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
setCurrentUserInfo(getUserData(user.email));
console.log("3" + currentUserInfo);
}
});
}, []);
const getUserData = (email) => {
let userdata;
const userData = collection(db, "users");
getDocs(query(userData, where("email", "==", `${email}`))).then(
(querySnapshot) => {
userdata = querySnapshot.docs.map((doc) => doc.data());
console.log("1" + querySnapshot.docs.map((doc) => doc.data()));
}
);
console.log("2" + userdata);
return userdata;
};
return (
<View>
<Text>{currentUserInfo.username}</Text>
</View>
);
};
export default test;