Implement infinite scroll 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 downloads the last 5 posts and downloads new posts. However, I would also like to be able to download old messages. I have a button that, when clicked, calls a function (which I don’t know how to implement it) that loads older messages. How to get these old messages?

(The arrow simply means that I want to receive messages starting from the bottom and working to the very top)

+4
source share
1 answer

You need to think a little back to do this. When you get the results for your query for the first page, remember the first element 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 elements by index using Firebase, you can save the element key and use it to run the 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> }); 

You now have the variable firstKnownKey, which has the first key you have ever seen. To get the previous batch of children, you pass this value to endAt() when you run the following 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 over the past few days:

+9
source

Source: https://habr.com/ru/post/1011596/


All Articles