Below is the code I have tried.Am really new to programming
var records_per_page = 4;
var first = firebase.firestore().collection("Posts").limit(records_per_page);
first.get().then((snapshot)=>
{
document.getElementById("post-container").innerHTML = '';
snapshot.forEach(function (taskValue) {
if(snapshot.size >= 1){
showPosts(taskValue)
$("#next").click(function(){
var lastVisible = "";
lastVisible = snapshot.docs[snapshot.docs.length-1];
showMorePosts(records_per_page,lastVisible)
})
}
});
}
);
But the code fetches the first and second four documents only. I have created a gist here to show both methods showMorePosts(records_per_page,lastVisible) and showPosts(records_per_page). Stackoverflow doesn't allow me to add a lot of code.
You can use offset
to load the page
const records_per_page = 4;
const page = 2;
const first = firebase.firestore().collection("Posts")
.limit(records_per_page)
.offset((page - 1) * records_per_page);
first.get().then(snapshot => {
document.getElementById("post-container").innerHTML = '';
snapshot.forEach(taskValue => {
// You don't need this if condition. It's impossible that this condition evaluates to false
// if (snapshot.size >= 1) {
showPosts(taskValue);
$("#next").click(() => {
const lastVisible = "";
lastVisible = snapshot.docs[snapshot.docs.length-1];
showMorePosts(records_per_page,lastVisible);
});
// }
});
});
As mentioned by @jabaa, use offset
to load a specific page. Look at an example below:
let query = firestore.collection('col').where('foo', '>', 42);
query.limit(10).offset(20).get().then(querySnapshot => {
querySnapshot.forEach(documentSnapshot => {
console.log(`Found document at ${documentSnapshot.ref.path}`);
});
});
Refer to the documentation on how to paginate a query. Here you can find the examples on query pagination.
I managed to create some sort of pagination so that when a person clicks next button, the next set of four posts replaces the former, continuously. However, am still figuring out on how to implement the previous button functionality so a person can load the previous sets of posts without having to refresh the page. I created a gist here . You can check it out for further progress and advise.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.