Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
How to query Realtime Database between a certain range

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:

enter image description here

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):

enter image description here

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

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!