Paginate with Descending Timestamp in Firestore

Viewed 279

Im having trouble paginating data by its descending timestamp in Firestore (fetch newest first). When I order by

Firestore.firestore().collection("items")
        .order(by: "date", descending: true)
        .limit(to: 3)

it works, but if I try to refresh it just loads the same data. To paginate I tried

Firestore.firestore().collection("items")
        .order(by: "random", descending: true)
        .start(after: [lastFetchedItem?.random ?? ""])
        .limit(to: 1)

which fetches data based on a random number generator and it paginates perfectly each time so I know its possible. Now if I try

Firestore.firestore().collection("items")
        .order(by: "date", descending: true)
        .start(after: [lastFetchedItem?.date ?? ""])
        .limit(to: 1)

I load the first item but can't paginate to the next. I record the timestamp with Timestamp(date: Date()) and in my dictionary my date is written as

var date: Date?
    
    init(dictionary: [String: Any]) {
        self.date = dictionary["date"] as? Date
    }
2 Answers

To paginate, pass in the entire snapshot of the last item on the previous page. Passing in single values as you do is not going to work.

So if your lastFetchedItem is the document snapshot:

Firestore.firestore().collection("items")
        .order(by: "date", descending: true)
        .start(after: lastFetchedItem)
        .limit(to: 1)

I ended up formatting the date field as a unix timestamp which gave me an Int such as I did with .random. Then I ordered by the date. Works perfectly.

Related