Skip to content
Advertisement

Why does startAfter in this firebase query isn’t working?

I have the next function using firebase in an JavaScript app. The query works fine the first time because lastDoc isn’t defined so it gets the first 7 documents in the database, but the next time when there’s a lastDoc, the query keeps returning the same first 7 docs. The lastDoc variable is updated and indeed gets the value of the next doc.

JavaScript

The first time the lastDoc is undefined, and returns docs 1, 2, 3, 4, 5, 6 and 7. The second time the lastDoc is:

JavaScript

, and keeps returning docs 1, 2, 3, 4, 5, 6 and 7

Why isn’t it working?

Advertisement

Answer

In the legacy version of the JavaScript SDK, startAfter was defined as:

JavaScript

In the modern JavaScript SDK, startAfter is defined as:

JavaScript

This means that your code should be functioning as expected. HOWEVER, based on the provided project code from the comments, this is for an Express API, not client-side JavaScript.

Your query isn’t working as expected because lastDoc is not a true DocumentSnapshot object at all and is instead a JavaScript version of it churned out by res.json(). Instead of returning a mangled DocumentSnapshot object to the client, we should instead just send back the data we need to pass as the startAfter arguments. In our case, we’ll send back just the updateDate parameter inside of lastDocData:

JavaScript

Then when the data comes back to the API, we’ll pass it to startAfter:

JavaScript

While reviewing methods/getPosts.ts, I noticed lines similar to the following:

JavaScript

Because query takes a variable number of arguments, you can use the spread operator (...) to optionally include some arguments. As a simplified example:

JavaScript

This allows you to use the following query builder instead:

JavaScript

Bringing this all together gives:

JavaScript
JavaScript
Advertisement