Due to the inclusive nature of the endAt()
function, I noticed that the last item was being repeated each time I executed infinite scroll. To address this issue, I made some adjustments based on a suggestion from Frank Van Puffen's solution.
I created a list called childrenVal
to hold all the values, another list named childrenKey
to store the keys, and initialized a variable called firstKnownKey
, as recommended by Frank Van Puffen.
var childrenVal=[];
var childrenKey=[];
var firstKnownKey = "";
Initially, when making the query for the first time, I fetched the last 5 elements:
getFirst(){
firebaseRef.orderByKey().limitToLast(5).once('value')
.then((snap)=>{
snap.forEach(childSnap => {
childrenVal.unshift(childSnap.val());
childrenKey.unshift(childSnap.key);
});
firstKnownKey = childrenKey[childrenKey.length-1];
});
}
For subsequent queries, to prevent any repetition of the firstKnownKey
, I implemented the following function:
exclude(key){
return key.substring(0, key.length - 1) + String.fromCharCode(key.charCodeAt(key.length - 1) - 1)
}
And for the actual query execution, I utilized the following function:
getNext() {
firebaseRef.orderByKey().endAt(exclude(firstKnownKey)).limitToLast(5).once('value')
.then((snap) => {
snap.forEach(childSnap => {
childrenVal.unshift(childSnap.val());
childrenKey.unshift(childSnap.key);
});
firstKnownKey = childrenKey[childrenKey.length - 1];
});
}