Tom Maton
Tom Maton

Reputation: 1594

Firebase results range using startAt and endAt

I'm trying to get the first 100 results from my Firebase data, then the next 100, then the next 100 etc. I've tried multiple ways.

Version 1

ref.child('products').orderByChild('domain').startAt(0).endAt(100).once('value').then(function(snapshot) {});

Version 2

ref.child('products').orderByChild('domain').startAt(0).limitToFirst(100).once('value').then(function(snapshot) {});

Version 3

ref.child('products').startAt(0).endAt(100).once('value').then(function(snapshot) {});

Every time the snapshot returned is null. Is there anyway in Firebase of getting the range of data I'm after?

Upvotes: 6

Views: 13734

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599661

When you call orderByChild() any subsequent call to startAt(), endAt() or equalTo() expects the value that you pass in to be a child. You're passing in an index. Unless the value of domain is a sequential index (highly unlikely), this will not work.

What you should do is remember the domain value of the last child you got, and then pass that in to startAt() for the next "page".

var productsRef = ref.child('products');
var lastKnownDomainValue = null;
var pageQuery = productsRef.orderByChild('domain').limitToFirst(100);
pageQuery.once('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    lastKnownDomainValue = childSnapshot.child('domain').val();
  });
});

Now you have a variable lastKnownDomainValue that has the last domain you've ever seen. To get the next batch of children, you pass that value in to startAt():

var nextQuery = productsRef.orderByChild('domain').startAt(lastKnownDomainValue).limitToFirst(100);

And then you update lastKnownDomainValue when you loop over the children again.

Upvotes: 10

Related Questions