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

142
Vistas
Firestore + React - Listen user posts deletions (dynamic number of documents)

I am implementing a custom hook in React "useFetchUserPosts" which, currently, is listening to new posts and provides a method "getMorePosts" that requests the DB (looking for old posts) using pagination.

export default function useFetchUserPosts(userData) {
  const cards = useCards();

  const [posts, setPosts] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  const startAfter = useRef(new Date());

  const handleNextPostsChanges = async (querySnapshot) => {
    const changes = querySnapshot.docChanges();

    const newPosts = [];

    await Promise.all(
      changes.map(async (change) => {
        if (change.type === "added") {
          const newPost = await parseUserPost(change.doc, false);
          newPosts.unshift(newPost);
        }
      })
    );

    if (!newPosts.length) return;

    cards.addCards(newPosts);

    setPosts((prevPosts) => [...newPosts, ...prevPosts]);
  };

  ...

  const getMorePosts = (limit = MAX_USER_POSTS_TO_RETRIEVE) => {
    ... perform a paginated request with the help of cursors
  }

  useEffect(() => {
    // We will only listen new posts from the current user.
    if (userData.id !== getCurrentUser().uid) {
      return;
    }

    const listener = listenUserPosts(
      userData.id,
      startAfter.current,
      MAX_USER_POSTS_PER_DAY, // 5
      handleNextPostsChanges,
      handleOnListenPostsError
    );

    return () => {
      listener();
    };
  }, []);

  useEffect(() => {
     // Retrieve the first amount of old posts
     getMorePosts();
  }, []);

  return {
     posts,
     isLoading,
     getMorePosts
  }
}

As you can see, I am subscribing to the new posts of the current user inside the use effect.

How can I do for listening to posts deletions? I mean, as I am using pagination, the length of the posts to listen its deletion can change... so, how can I do for listening a dynamic number of documents?


Note: This is my code for listening user posts:

export function listenUserPosts(
  userId,
  startAt = undefined,
  limitToLast = MAX_USER_POSTS_PER_DAY,
  onNext,
  onError
) {
  let query = firestore
    .collection("posts")
    .doc(userId)
    .collection("userPosts")
    .orderBy("date");

  if (startAt) {
    query = query.startAt(startAt);
  }

  // TODO - Parse docs here instead of inside components.
  return query.limitToLast(limitToLast).onSnapshot(onNext, onError);
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use the onSnapshot() method to listen to multiple documents in a collection. Every time the query results change which means that whenever a document is added, removed, or modified, the snapshot handler will receive a new query snapshot.

about 4 years ago · Juan Pablo Isaza Denunciar
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