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

119
Views
Build Firebase queries dynamically

I'm wondering if it's possible to build firebase queries dynamically, at the moment I'm using a variable to determine if startAfter should be included or not.

As you can see this is causing duplicate code, for just one variable

export async function fetchUserPhotosPaginated(userId: string, lastUserPhoto?: QueryDocumentSnapshot): Promise<QuerySnapshot> {
    if (lastUserPhoto) {
        return await getDocs(query(
            collection(db, 'photos'),
            orderBy('createdAt', 'desc'),
            startAfter(lastUserPhoto),
            where('user.id', '==', userId),
            limit(5)
        ))
    }

    return await getDocs(query(
        collection(db, 'photos'),
        orderBy('createdAt', 'desc'),
        where('user.id', '==', userId),
        limit(5)
    ))
}

I've tried

  • Use startAfter(null), this did not give the intended effect
  • assign the query to a variable let q = query(...) to then update that query using q = q.startAfter(...) this also did not work
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The second method of adding startAfter conditionally is correct but your syntax to update query is not. Try refactoring the function as shown below:

export async function fetchUserPhotosPaginated(userId: string, lastUserPhoto?: QueryDocumentSnapshot): Promise<QuerySnapshot> {
  // Initial query
  let q = query(collection(db, 'posts'), orderBy('createdAt', 'desc'))
  
  // Add startAfter is lastUserPhoto is present    
  if (lastUserPhoto) q = query(q, startAfter(lastUserPhoto));
  
  // Add remaining conditions
  q = query(q, where('user.id', '==', userId), limit(5)); 

  return await getDocs(q)
}

You can also add all conditions in an array as explained in following answer:

Firestore conditional where clause using Modular SDK v9

about 4 years ago · Juan Pablo Isaza 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!