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);
}
};