Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda