I've done loads of searching around trying to find a helpful post or article on this subject and so far with no luck. There are plenty of pagination/infinite scroll tutorials but these are Angular tutorials I would prefer to keep it pure and simple JS.
What I want to do is lazy load data in from Firestore as the user scrolls down a div. So initially loading a small set of the data in and then bring in more as the user scrolls. So far I have the following code:
firebase.initializeApp({
apiKey: "AIzaSyDEkmqcwWFz6xCYAuS1jXCBcpxzCv_IlBE",
authDomain: "test-903a0.firebaseapp.com",
databaseURL: "https://test-903a0.firebaseio.com",
projectId: "test-903a0",
storageBucket: "test-903a0.appspot.com",
messagingSenderId: "117341455405"
});
// Initialize Cloud Firestore through Firebase
const db = firebase.firestore();
var first = db.collection("users").orderBy("first").limit(2);
first.get().then(function (documentSnapshots) {
var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
documentSnapshots.forEach(function(doc) {
$('#myTable').append('<tr><td>' + doc.data().first + '</td><td>' + doc.data().last + '</td><td>' + doc.data().born + '</td></tr>');
})
var next = db.collection("users").orderBy("first").startAfter(lastVisible).limit(2);
jQuery(function($) {
$('.scroll').on('scroll', function() {
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
next.get().then(function (documentSnapshots) {
documentSnapshots.forEach(function(doc) {
$('#myTable').append('<tr><td>' + doc.data().first + '</td><td>' + doc.data().last + '</td><td>' + doc.data().born + '</td></tr>');
});
});
};
});
});
});
.scroll {
height: 400px;
width: 400px;
overflow: scroll;
}
.table-container {
height: 1000px;
}
#myTable {
border-collapse: collapse;
width: 100%;
}
#myTable, th, td {
border-bottom: 1px solid #ddd;
}
#myTable tr:nth-child(even) {
background-color: #f2f2f2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script defer src="/__/firebase/init.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase-firestore.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="scroll">
<div class="table-container">
<table id="myTable">
<tbody>
</tbody>
</table>
</div>
</div>
When I scroll this div it loads the next 2 results in from the firestore database. However, when scrolling thereafter, it simply loads the previous 2 results back into the table. Can someone please advise me where I'm going wrong here as I'm at a loss?