0

I am calling data from firestore and paginating them. This is my query:

const tradesRef = firebase
    .firestore()
    .collection("trades")
    .orderBy("quoteQty", "desc")
    .where("quoteQty", ">", 5000)
    .limit(12);

useEffect(() => {
    tradesRef.get().then((collections) => {
      const tradesData = collections.docs.map((trade) => trade.data());
      const lastDoc = collections.docs[collections.docs.length - 1];
      setTrades(tradesData);
      setLastTrades(lastDoc);
    });
    setDataLoading(false);
  }, []);

I am using this function to get the next 12 trades:

const fetchMore = () => {
    tradesRef
      .startAfter(lastTrades)
      .get()
      .then((collections) => {
        const tradesData = collections.docs.map((trade) => trade.data());
        const lastDoc = collections.docs[collections.docs.length - 1];
        setTrades(tradesData);
        setLastTrades(lastDoc);
      });
  };

I am trying to give a previous page option but can not figure out how to go to the previous page. So far I have tried this which does not work:

const fetchPrevious = () => {
    tradesRef
      .endBefore(lastIndex)
      .limitToLast(12)
      .get()
      .then((collections) => {
        const tradesData = collections.docs.map((trade) => trade.data());
        const lastDoc = collections.docs[collections.docs.length - 1];
        setTrades(tradesData);
        setLastTrades(lastDoc);
      });
  };

Any suggestions on how can I make the previous button work?

  • Does this answer your question? [Firestore pagination by offset](https://stackoverflow.com/questions/62951311/firestore-pagination-by-offset) – jsonderulo Feb 10 '22 at 19:03
  • It only explains the next page which is already implemented. I am looking for previous page – Husnain Mehmood Feb 10 '22 at 19:06
  • it also explains that firestore limit always starts from the beginning – jsonderulo Feb 10 '22 at 19:07
  • Yes that is what I am going for. I am just looking for a way to go back to the previous page. – Husnain Mehmood Feb 10 '22 at 19:16
  • Does this [post](https://stackoverflow.com/questions/53044791/) answers your question? Using `startAt()` can help to achieve this task, but there are several other examples in the answers. – Alex Feb 11 '22 at 18:35
  • this post might help where I found the solution https://stackoverflow.com/questions/73915730/unable-to-get-previous-data-properly-during-pagination-using-firestore-in-react/73921307#73921307 – James Oct 01 '22 at 19:54

0 Answers0