使用firestore分页获取以前的文档



我正在使用Firestore数据库来存储我的加密交易。由于它们有很多,所以我必须使用.limit(numberOfTrades)查询来加载它们。

我的查询:const tradesRef = firebase.firestore().collection("trades").limit(15);

内部我的使用效果:

useEffect(() => {
tradesRef
.where("type", "==", "fiveMinutes")
.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);
}, [filter]);

然而,为了加载下一组交易,我确实需要分页。next的分页已经实现并且相当简单。这是我在下一页使用的功能:

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);
});
}

现在我正试图弄清楚如何实现前12笔交易的前一个页面查询。我已经研究并实现了一些查询,但我甚至还没有接近解决这个问题。如有任何帮助,我们将不胜感激。

如果你想向后分页,你需要使用以下的组合:

.endBefore(firstItemOnNextPage)
.limitToLast(12)

所以firstItemOnNextPage是第N+1页上的第一个项目,从这里向后分页。然后你要在那个锚定项目之前的最后12个项目。

最新更新