Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda