Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase-firestore.js"></script>
  <title>Firestore virtual scroll</title>
</head>
<body>
  <ol>
    <li>This shows an anchor document, based on its "index" field.
      <ul id="anchor"></ul>
    <li>This is the next page of documents.
      <ul id="down"></ul>
    <li>This is the previous page of documents. 
      <ul id="up"></ul>
    <li>This is what I'd like to do, based on RTDB
      <ul id="test"></ul>
  </ol>
</body>
</html>
 
// show loading data for a previous page in Firestore
var config = {
    apiKey: "AIzaSyDdoix2XvC2r_xyIDtOFL5Hzjb0uMP-XZU",
    authDomain: "large-firestore.firebaseapp.com",
    databaseURL: "https://large-firestore.firebaseio.com",
    projectId: "large-firestore",
    storageBucket: "large-firestore.appspot.com",
    messagingSenderId: "238599175308"
};
firebase.initializeApp(config);
//firebase.firestore.setLogLevel('debug');
var db = firebase.firestore();
var docs = db.collection("1k");
var anchorElm = document.getElementById("anchor"),
    upElm = document.getElementById("up"),
    downElm = document.getElementById("down"),
    testElm = document.getElementById("test");
// step 1: find the anchor document by its 'index' field
docs.where("index", "==", 100).get().then((querySnapshot) => {
  console.log(querySnapshot.docs[0]);
  var anchorDoc = querySnapshot.docs[0];
  addDocTo(anchorDoc, anchorElm)
  
  // Step 2: show the next page of documents
  docs.orderBy("index").startAfter(anchorDoc).limit(3).get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      addDocTo(doc, downElm);
    })
  })
  // Step 3: show the previous page of documents
  docs.orderBy("index", "desc").startAfter(anchorDoc).limit(3).get().then((querySnapshot) => {
    // TODO: we need to reverse the results to get them in the right order
    querySnapshot.forEach((doc) => {
      addDocTo(doc, upElm);
    })
  })
  // Alt 3: this is how I'd expect the previous page to be loaded
  docs.orderBy("index").endBefore(anchorDoc).limit(3).get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      addDocTo(doc, testElm);
    })
  })
});
function addDocTo(doc, container) {
  let li = document.createElement("li");
  li.id = doc.id;
  li.innerText = doc.id+": "+doc.data().index;
  container.appendChild(li);
}
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
pufpro
0viewers