Bird
Raised Fist0
Firebasecloud~10 mins

Limit and pagination in Firebase - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Limit and pagination
Start Query
↓
Apply Limit N
↓
Fetch First N Items
↓
Display Items
↓
User Requests Next Page
↓
Use Last Item as Cursor
↓
Fetch Next N Items After Cursor
↓
Repeat Display and Pagination
The query first limits results to N items, then uses the last item as a cursor to fetch the next page when requested.
Execution Sample
Firebase
db.collection('posts')
  .orderBy('date')
  .limit(3)
  .get()
  .then(snapshot => {
    // display first 3 posts
  })
Fetches the first 3 posts ordered by date from the database.
Process Table
StepActionQuery StateResultNotes
1Start query with orderBy('date')No limit, no cursorQuery readyInitial query setup
2Apply limit(3)Limit set to 3Query readyLimits results to 3 items
3Execute get()Limit=3, no cursorFetch first 3 postsReturns first page
4Display postsShowing 3 postsPosts 1,2,3 shownUser sees first page
5User requests next pageCursor set to last post (post 3)Prepare next queryUse last item as cursor
6Query with startAfter(post 3) and limit(3)Limit=3, cursor=post 3Fetch posts after post 3Fetch next page
7Execute get()Limit=3, cursor=post 3Fetch posts 4,5,6Returns second page
8Display postsShowing posts 4,5,6Posts 4,5,6 shownUser sees second page
9User requests next pageCursor set to last post (post 6)Prepare next queryRepeat pagination
10Query with startAfter(post 6) and limit(3)Limit=3, cursor=post 6Fetch posts after post 6Fetch third page
11Execute get()Limit=3, cursor=post 6Fetch posts 7,8,9Returns third page
12Display postsShowing posts 7,8,9Posts 7,8,9 shownUser sees third page
13User requests next pageCursor set to last post (post 9)Prepare next queryIf no more posts, empty result
14Query with startAfter(post 9) and limit(3)Limit=3, cursor=post 9Fetch posts after post 9No more posts
15Execute get()Limit=3, cursor=post 9Empty resultNo more pages
16Display postsNo posts to showEmpty pagePagination ends
💡 No more posts after last cursor, pagination ends
Status Tracker
VariableStartAfter Step 3After Step 7After Step 11After Step 15
limitundefined3333
cursorundefinedpost 3post 6post 9post 9
fetchedPosts[][post1, post2, post3][post4, post5, post6][post7, post8, post9][]
Key Moments - 3 Insights
Why do we need to use the last item as a cursor for the next page?
Because Firebase queries use cursors to know where to start fetching next items. The last item of the current page marks the starting point for the next query (see steps 5 and 6 in execution_table).
What happens if we don't use limit() in the query?
Without limit(), the query fetches all matching items at once, which can be slow and inefficient. Limit controls how many items are fetched per page (see step 2).
Why does the pagination stop after some pages?
Pagination stops when the query returns no more items after the cursor, meaning all data has been fetched (see steps 14-16).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 7, how many posts are fetched?
A3 posts
B6 posts
CNo posts
D1 post
💡 Hint
Check the 'Result' column at step 7 in execution_table
At which step does the cursor first get set to post 6?
AStep 7
BStep 5
CStep 9
DStep 3
💡 Hint
Look at the 'cursor' variable changes in variable_tracker after each step
If we change limit(3) to limit(5), how would the fetchedPosts array change after step 3?
AIt would fetch 3 posts still
BIt would fetch 5 posts instead of 3
CIt would fetch no posts
DIt would fetch all posts
💡 Hint
Limit controls how many posts are fetched per query (see step 2 and variable_tracker)
Concept Snapshot
Firebase pagination uses limit() to fetch a fixed number of items.
Use startAfter(lastItem) as a cursor to fetch the next page.
Repeat queries with updated cursor to paginate through data.
Stop when query returns no more items.
This approach avoids loading all data at once and improves performance.
Full Transcript
This visual execution shows how Firebase limit and pagination work step-by-step. First, a query orders posts by date and limits results to 3 items. The first 3 posts are fetched and displayed. When the user requests the next page, the last post from the previous page is used as a cursor with startAfter() to fetch the next 3 posts. This process repeats until no more posts are available, ending pagination. Variables like limit, cursor, and fetchedPosts change as the query progresses. Key moments clarify why cursors and limits are needed and when pagination stops. The quiz tests understanding of fetched items, cursor updates, and limit effects. This method efficiently loads data in pages rather than all at once.

Practice

(1/5)
1. What does the limit() function do in Firebase queries?
easy
A. It restricts the number of documents returned by the query.
B. It sorts the documents in ascending order.
C. It filters documents based on a condition.
D. It deletes documents from the collection.

Solution

  1. Step 1: Understand the purpose of limit()

    The limit() function is used to control how many documents are returned in a query result.
  2. Step 2: Compare options with limit() behavior

    Only It restricts the number of documents returned by the query. correctly describes that limit() restricts the number of documents returned.
  3. Final Answer:

    It restricts the number of documents returned by the query. -> Option A
  4. Quick Check:

    limit() controls result count = B [OK]
Hint: Limit sets max items returned in query [OK]
Common Mistakes:
  • Confusing limit() with orderBy()
  • Thinking limit() filters data
  • Assuming limit() deletes data
2. Which of the following is the correct syntax to get the first 5 documents ordered by 'timestamp' in Firebase?
easy
A. db.collection('posts').limit(5).orderBy('timestamp')
B. db.collection('posts').orderBy('timestamp').limit(5)
C. db.collection('posts').limit(5, 'timestamp')
D. db.collection('posts').orderBy('timestamp', 5)

Solution

  1. Step 1: Recall correct method chaining order

    In Firebase, orderBy() must come before limit() to sort then limit results.
  2. Step 2: Check each option's method order and parameters

    db.collection('posts').orderBy('timestamp').limit(5) correctly orders by 'timestamp' then limits to 5 documents. Others have wrong order or invalid parameters.
  3. Final Answer:

    db.collection('posts').orderBy('timestamp').limit(5) -> Option B
  4. Quick Check:

    orderBy before limit = C [OK]
Hint: Always orderBy before limit in Firebase queries [OK]
Common Mistakes:
  • Placing limit() before orderBy()
  • Passing limit a field name
  • Using orderBy with a number parameter
3. Given this Firebase query code:
const firstPage = await db.collection('items').orderBy('name').limit(3).get();
const lastVisible = firstPage.docs[firstPage.docs.length - 1];
const nextPage = await db.collection('items').orderBy('name').startAfter(lastVisible).limit(3).get();
console.log(nextPage.docs.length);

What will be printed if the collection has 7 documents?
medium
A. 3
B. 4
C. 7
D. 0

Solution

  1. Step 1: Analyze first page query

    The first query orders by 'name' and limits to 3 documents, so it gets documents 1 to 3.
  2. Step 2: Analyze next page query

    The next query starts after the last document of the first page and limits to 3 documents. Since total is 7, remaining documents are 4 (docs 4 to 7), but limit(3) returns 3 documents.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    7 total - 3 first page = 4 remaining, limit(3) = 3 [OK]
Hint: Subtract first page count from total for next page size [OK]
Common Mistakes:
  • Assuming next page always has same limit count
  • Ignoring startAfter effect
  • Counting all documents again
4. You wrote this Firebase pagination code but it throws an error:
const firstPage = await db.collection('users').limit(5).orderBy('age').get();

What is the error and how to fix it?
medium
A. Error: get() must be called before limit(); call get() first.
B. Error: limit() requires a field name; add 'age' as parameter.
C. Error: orderBy must come before limit; fix by swapping the methods.
D. No error; code works fine.

Solution

  1. Step 1: Identify method order error

    Firebase requires orderBy() before limit() to sort data before limiting.
  2. Step 2: Fix by swapping method calls

    Change code to db.collection('users').orderBy('age').limit(5).get() to fix the error.
  3. Final Answer:

    Error: orderBy must come before limit; fix by swapping the methods. -> Option C
  4. Quick Check:

    orderBy before limit fixes error = A [OK]
Hint: Always call orderBy before limit to avoid errors [OK]
Common Mistakes:
  • Calling limit before orderBy
  • Passing field name to limit
  • Calling get() too early
5. You want to paginate through a Firebase collection with 12 documents, showing 5 per page. After fetching the first two pages, how many documents will the third page query return?
hard
A. 0
B. 3
C. 5
D. 2

Solution

  1. Step 1: Calculate documents fetched in first two pages

    Each page shows 5 documents, so first two pages fetch 5 + 5 = 10 documents.
  2. Step 2: Calculate remaining documents for third page

    Total documents are 12, so remaining are 12 - 10 = 2 documents.
  3. Step 3: Consider limit on third page

    Limit is 5, but only 2 documents remain, so third page returns 2 documents.
  4. Final Answer:

    2 -> Option D
  5. Quick Check:

    12 - 10 = 2 documents left for page 3 [OK]
Hint: Subtract fetched docs from total to find last page size [OK]
Common Mistakes:
  • Assuming all pages have full 5 documents
  • Ignoring total document count
  • Confusing page number with document count
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard