0

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);
    });
  }, []);
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
tnocs
  • 59
  • 5
  • This has nothing to do with the Firebase SDK version. The main problem is that you can't use an async function call like `getDoc` inside a `forEach` loop. and expect it to complete before the loop ends. You will need to restructure your code so that the call to `setAllComments` happens only after all the async document fetches are fully complete. – Doug Stevenson Jan 19 '23 at 19:42
  • I know it doesn't have anything to do with the version, but the solutions I got from chatGPT wouldn't help me :-) – tnocs Jan 19 '23 at 19:43
  • 1
    ChatGPT does not really understand how to program a computer, it turns out. – Doug Stevenson Jan 19 '23 at 19:44

0 Answers0