Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Infinite Scrolling with Firebase?

      var self = this;
      var firebaseRef = new Firebase(baseUrl + '/sparks');

      firebaseRef.limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
        self.addChild(childSnapshot); // adds post to a <div>
      });

database layout

My code currently loads the last 5 posts and will load any new posts. However, I'd also like to be able to load older posts as well. I have a button that when clicked will call a function (that I'm unsure of how to implement) that loads older posts. How do I retrieve these older posts?

(The arrow just signifies that I want to retrieve posts starting from the bottom and working my way up to the top)

like image 932
Chris W Avatar asked Jan 30 '16 06:01

Chris W


1 Answers

You need to think a bit backwards to do this. When you get the results for your query for the first page, remember the first item in the results:

firebaseRef.endAt().limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
    self.addChild(childSnapshot); // adds post to a <div>
  });

While you cannot access child items by index with Firebase, you can store the key of an item and use that to start a next query.

var firstKnownKey;
firebaseRef.orderByKey().limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
    if (!firstKnownKey) {
      firstKnownKey = childSnapshot.key;
    }
    self.addChild(childSnapshot); // adds post to a <div>
});

Now you have a variable firstKnownKey that has the first key you've ever seen. To get the previous batch of children, you pass that value in to endAt() when you fire your next query:

firebaseRef.orderByKey().endAt(firstKnownKey).limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
    if (!firstKnownKey) {
      firstKnownKey = childSnapshot.key;
    }
    self.addChild(childSnapshot); // adds post to a <div>
});

Answers to similar questions of the past few days:

  • Can I get the nth item of a firebase "query"?
  • Firebase results range using startAt and endAt
like image 100
Frank van Puffelen Avatar answered Oct 10 '22 04:10

Frank van Puffelen