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

114
Views
Multiple firestore onSnapshot on single setState

My goal is that, on my Following page, I should get all the events that I created and also all events that the users that I followed created. I am trying to implement a onSnapshot for the current user, and onSnapshot for each user that the current user is following.

Here's how I did my code:

useEffect(() => {
    if (user.id) {
      let subscribers = [];

      const mainSubscriber = db
        .collection('Events')
        .doc(user.id)
        .collection('following')
        .onSnapshot(snapshot => {
          const docs = snapshot.docs.map(d => d.data());
          const events = formatEvents(docs);

          setItemsByUser({...itemsByUser, [user.id]: events});
        });

      subscribers.push(mainSubscriber);

      if (users && users.length) {
        for (const u of users) {
          const sub = db
            .collection('Events')
            .doc(u.id)
            .collection('followers')
            .onSnapshot(snap => {
              const docs = snap.docs.map(d => d.data());
              const events = formatEvents(docs);

              if (docs.length) {
                setItemsByUser({...itemsByUser, [u.id]: events});
              }
            });

          subscribers.push(sub);
        }
      }

      return () => subscribers.forEach(sub => sub());
    }
  }, [user.id]);

But the problem im facing is that all onSnapshot starts with itemsByUser with empty object which means every setItemsByUser will only set the events of that user, i tried adding setTimeout but it didnt work. Please help me.

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!