I was trying to fetch data from my firebase firestore data base ! i had to make nested forEach one to get the users and the second one to get the posts of each user But the problem that the posts are showing in my screen for 1second then disappear for no reason ? im think its that return ! its returning before the foreach finish maybe ? but if that is the case it should REreturn when it's finished , if i console log posts after setPosts it shows me the array of the posts but if i console log the res (return) it shows me an empty array !!!! any solution to that ?
const [posts, setPosts] = useState([]);
useEffect(() => {
const fetchPosts = async () => {
let POSTS = [];
const docRef = collection(db, "users");
const snapshot = await getDocs(docRef);
snapshot.forEach(async (doc) => {
let docRefTwo = collection(db, "users", doc.id, "posts");
let snapshotTwo = await getDocs(docRefTwo);
snapshotTwo.forEach((post) => {
POSTS.push({ postId: post.id, ...post.data() });
});
});
return POSTS;
};
fetchPosts().then((res) => {
setPosts(res);
});
}, []);