Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
nested forEach while fetching from firebase causing problems

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);
   });
 }, []);
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!