I know similar questions have been asked here: I need to pull data from another Firestore collection based on forEach data within a onSnapshot call and here: Using getDoc().then() inside of a loop Firebase but I really cannot adapt it to my own issue. I actually also consulted ChatGPT, but apparently, it only knows firebase v8.x.x :/
I have a comment collection and I'm querying these for specific content (url). I can get the comments in the first step just fine. Each comment document has a field called "user_id", I want to use this user ID to get information about the user from the collection "userinfo" and push it to the comments array. From what I can understand, the promise I get in my attempt (see code below), indicates that I need to use await, but this is apparently tricky in for loops and inside useEffect.
My attempt is below:
const [allCommments, setAllCommments] = useState([]);
const commentRef = collection(db, "comments");
const q = query(commentRef, where("content", "==", url));
useEffect(() => {
onSnapshot(q, (snapshot) => {
const tempComments = [];
snapshot.forEach((snapDoc) => {
tempComments.push(snapDoc); // this works fine, the next steps doesn't:
const userSnap = getDoc(doc(db, "userinfo", snapDoc.data().user_id));
// tempComments.push(userSnap.data().firstname).push(userSnap.data().lastname) // what I want
// console.log(userSnap.data()) // this gives the error "userSnap.data() is not a function"
// console.log(userSnap); // this only returns a promise
});
setAllCommments(tempComments);
});
}, []);