I want to be able to retrieve the users from the Firestore database and filter to find a match between the id of the current logged in user with the id of the user from the database. I am not able to do that because I can't figure out a way to change this to async function:
const [loggedUser, setLoggedUser] = useState([]);
const [data, setData] = useState([]);
useEffect(() => {
const getUserData = () => {
onSnapshot(collection(db, "users"), (snapshot) => {
let list = [];
snapshot.docs.forEach((doc) => {
list.push({ id: doc.id, ...doc.data() });
setData(list);
});
}, (err) => {
console.log(err);
});
}
getUserData();
}, [])
useEffect(() => {
const getLoggedUser = onAuthStateChanged(auth, (user) => {
if (user) {
const uid = user.uid;
console.log(uid);
if (data) {
const signedUser = data.filter((item) => item.id === uid);
setLoggedUser(signedUser);
} else {
console.log("no matching data")
}
} else {
console.log("no user found")
}
});
getLoggedUser();
}, [])
I want to be able to retrieve the users from the Firestore database and filter to find a match between the id of the current logged in user with the id of the user from the database.
You can use getDoc instead that'll only fetch the user's document and will cost you only 1 read. Currently you are reading the whole collection that'll cost you N reads where N is number of documents in the users collection.
You can use useEffect() just once and query Firestore when the auth state has been updated. Try refactoring the code as shown below:
import { getDoc, doc } from "firebase/firestore"
const [loggedUser, setLoggedUser] = useState([]);
const [data, setData] = useState([]);
useEffect(() => {
onAuthStateChanged(auth, (user) => {
if (user) {
const uid = user.uid;
console.log("User UID:", uid);
const snapshot = await getDoc(doc(db, "users", uid));
if (snapshot.exists) {
setLoggedUser(snapshot.data());
} else {
console.log("user document missing")
}
} else {
console.log("User not logged in")
}
});
}, [])