Home > other >  How to load more data on click from Firestore
How to load more data on click from Firestore

Time:01-04

I'm fetching data from firestore with a set limit of data. At the bottom I have a button that is linked to a function FetchMore and I want more data to get loaded and added to the ElectroniquePosts state when I click on that button

Feed.js

function Feed() {
  const [ElectroniquePosts, setElectroniquePosts] = useState([]);
  const countRef = useRef(null);

  useEffect(() => {
    const unsubscribe = onSnapshot(
      query(
        collection(db, "ElectroniquePosts"),
        orderBy("timestamp", "desc"),
        limit(1)
      ),
      (snapshot) => {
        setElectroniquePosts(snapshot.docs);
      }
    );
    return () => {
      unsubscribe();
    };
  }, [db]);

  countRef.current = ElectroniquePosts.length;
  console.log("Number of docs : "   countRef.current);

  const FetchMore = (e) => {
    e.preventDefault();

    const unsubscribe = () =>
      onSnapshot(
        query(
          collection(db, "ElectroniquePosts"),
          orderBy("timestamp", "desc"),
          startAfter(countRef.current),
          limit(1)
        ),
        (snapshot) => {
          setElectroniquePosts(snapshot.docs);
        }
      );
    return unsubscribe();
  };

  return (
    <>
      {ElectroniquePosts.length === 0 ? (
        <div> </div>
      ) : (
        <>
          <div className="pb-20 flex flex-wrap justify-center "> </div>
          <div >
            <button onClick={FetchMore}>Load More </button>
          </div>
        </>
      )}
    </>
  );
}

export default Feed;

CodePudding user response:

Using the following Reference, I came up with a working code and this is what it now looks like

Feed.js

  const FetchMore = async () => {
    const FetchMoreElectronique = async () => {
      const first = query(
        collection(db, "ElectroniquePosts"),
        orderBy("timestamp", "desc"),
        limit(ElectroniquePosts.length)
      );
      const documentSnapshots = await getDocs(first);

      const lastVisible =
        documentSnapshots.docs[documentSnapshots.docs.length - 1];

      const next = query(
        collection(db, "ElectroniquePosts"),
        orderBy("timestamp", "desc"),
        startAt(lastVisible),
        limit(2)
      );
      const DocSnapshotNext = await getDocs(next);
      setElectroniquePosts(DocSnapshotNext.docs);
    };
    FetchMoreElectronique();
  };
  •  Tags:  
  • Related