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

140
Views
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 answers
Answer question

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 Report
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!