I'm implementing infinite scroll using Next.js and Firestore Realtime Database (v9.x).
When the client requests the home page, the server fetches the 4 most recent images from the database and displays them to the client. When the user reaches the bottom of the page, 4 more images should be fetched and so on.
This is my database:
Every time a user adds a new image, that image is pushed to the end of the list, just like an array/list.
For the first 4 images that are fetched in the server side and sent/displayed to the client, I'm using this code:
query(ref(db, 'latest_images'), limitToLast(4))
This code is intended to fetch the last four images added (the most recent images).
Now, on the client side, when the user reaches the end of the page, this is the code I'm using to fetch 4 more images:
query(
ref(db, `latest_images`),
endBefore(lastImageID), // lastImagedID = "-MqZdzr7RTYpyujV6hnP" (w/ d. quotes)
limitToLast(4),
)
The lastImageID stores the fourth entry key from the bottom up in the database image shown above. This variable is an "anchor" so the code knows where to start querying for the 4 next images.
What I expected from the code above is that it would fetch these images (delimited by the red braces):
But it ended up fetching the same 4 images that were fetched on the server side initially (delimited by the blue braces).
From the documentarion:
endBefore() Return items less than the specified key or value depending on the order-by method chosen.
limitToLast() Sets the maximum number of items to return from the end of the ordered list of results.
https://firebase.google.com/docs/database/web/lists-of-data?authuser=0#filtering_data
As we discussed in the comments, you'll have to tell the database what to order on, before you can filter the data. Since you're filtering on the keys, adding orderByKey() to your query will ensure it knows to filter on the keys.
I've filed a bug to get this clarified in the documentation snippets, as it's quite easy to misunderstand it now.