[英]How do I paginate my posts from firestore to my Javascript web app. Am not using any framework except Node.js server
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).
我在这里创建了一个要点来展示 showMorePosts(records_per_page,lastVisible) 和 showPosts(records_per_page) 两种方法。 Stackoverflow doesn't allow me to add a lot of code.
Stackoverflow 不允许我添加大量代码。
You can use offset
to load the page您可以使用
offset
加载页面
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.正如@jabaa 所提到的,使用
offset
来加载特定页面。 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.
您可以查看它以获得进一步的进展和建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.