0

I am trying to get data from a subcollection from Firestore. I don't even know if that is legal but I created a nested query because I want to put the data I retrieve into "list" array that's why I tried nesting them. The problem I'm having is that the outer loop finishes first then the inner starts. That prevents me from putting the data into "list array". How can I solve this?

  const fetchPosts = async () => {
    try {
      const list = [];

      
      const profileRef = firestore
        .collection("users")
        .doc(auth.currentUser.uid);
      const doc = await profileRef.get();
      setDoc(doc);

      await firestore
        .collection("posts")
        .orderBy("postTime", "desc")
        .get()
        .then((querySnapshot) => {
          //console.log("Total Posts: ", querySnapshot.size);
          querySnapshot.forEach((doc) => {
            const pId = doc.id;
            const path = [];

            firestore
            .collection("posts")
            .doc(pId)
            .collection("route")
            .get().then((querySnapshot)=>{

              querySnapshot.forEach((document) => {
                const array  = document.data();
                const route = Object.values(array)
                console.log("route",route)
                path.push(route)
              })
            })
            console.log("path",path)
            
            const {
              userId,
              userName,
              userSurname,
              post,
              postImg,
              postTime,
              userImg,
              like,
              comment,
              likeByUsers,
            } = doc.data();
            list.push({
              id: pId,
              userId,
              userName,
              userSurname,
              userImg: userImg,
              post,
              postImg,
              postTime: postTime,
              liked: false,
              like,
              comment,
              likeByUsers,
            });
          });
        });

      setPosts(list);

      if (loading) {
        setLoading(false);
      }
      //console.log("Posts: ", posts);
    } catch (e) {
      console.log(e);
    }
  };
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • It's because all the database operations are asynchronous and return immediately, even if you are using then/catch. Anything that returns a promise returns that promise immediately without waiting for the work to complete. The loop is just churning through them before they're done. – Doug Stevenson May 03 '22 at 17:13
  • Thank you for your answer. So I can't nest database operations. Is there a workaround to achieve what I'm trying to do? – Serhat Sergikaya May 03 '22 at 17:55
  • Read the marked duplicates. – Doug Stevenson May 03 '22 at 18:21

0 Answers0