I have a paginated list of posts, where my cursor is re-calculated on each fetch, assigning the last QuerySnapshot document to it:
// Calculate the new startAfter
if (querySnapshot.size) {
startAfter = querySnapshot.docs[querySnapshot.docs.length - 1];
}
Somehow, using doc snapshots as cursors is one of the most "secure" ways to avoid breaking paginations.
I am thinking about optimizing some parts of my app with denormalizations. For example, as each user of my app can upload infinite posts that are shown on their profiles 10 by 10, it might be a good idea to add the last 10 user posts (denormalization) to the user's document (an array field).
With this, I avoid making the first 10 post fetch of each visited profile. But... how do I assign the first startAfter cursor? I mean, is it possible to write a doc snapshot in a document or something like that to get the same behavior?
If you look at the documentation for startAfter, you'll see there are two overloads:
startAfter ( snapshot : DocumentSnapshot < any > ) : Query < T >Creates and returns a new
Querythat starts after the provided document (exclusive). The starting position is relative to the order of the query. The document must contain all of the fields provided in theorderByof this query.Parameters
snapshot:DocumentSnapshot<any>The snapshot of the document to start after.
And
startAfter ( ... fieldValues : any [] ) : Query < T >Creates and returns a new
Querythat starts after the provided fields relative to the order of the query. The order of the field values must match the order of the order by clauses of the query.Parameters
Rest ...fieldValues: any[]The field values to start this query after, in order of the query's order by.
Since you don't have a DocumentSnapshot, you can use the second overload and pass the relevant field values.