Firebase lazy load

余生长醉 提交于 2019-12-23 01:29:00

问题


I'm trying to lazy load firebase items to later on load more of them whenever user reaches end of div container. When i remove .endAt() and .startAt() i'm receiving the 15 items though they are not beeing incremented and it's stuck at these 15 items.

When i keep .endAt() and .startAt() i'm receiving firebase warning Using an unspecified index. Consider adding ".indexOn": "title" at /items even though .indexOn is set. I'm confused by that warning. Thanks in advance for any help.

Firebase structure

{
  "items" : {
    "-Kk6aHXIyR15XiYh65Ht" : {
      "author" : "joe", 
      "title" : "Product 1"
    },
    "-Kk6aMQlh6_E3CJt_Pnq" : {
      "author" : "joe",
      "title" : "Product 2"
    }
  },
  "users" : {
    "RG9JSm8cUndpjMfZiN6c657DMIt2" : {
      "items" : {
        "-Kk6aHZs5xyOWM2fHiPV" : "-Kk6aHXIyR15XiYh65Ht",
        "-Kk6aMTJiLSF-RB3CZ-2" : "-Kk6aMQkw5bLQst81ft7"
      },
      "uid" : "RG9JSm8cUndpjMfZiN6c657DMIt2",
      "username" : "joe"
    }
  }
}

Security rules

{
  "rules": {
    ".read": true,  
    ".write": "auth != null",  
    "users":{
      "$uid": {
        ".write": "$uid === auth.uid"
        "items":{
          ".indexOn": "title",
          "$itemId": {
            "title": {".validate": "...}
            "type": {".validate": "...}
            }
          }
        }
      }
    }
  }
}

Code structure for lazy load

let _start = 0,
    _end = 14,
    _n = 15;

function lazyLoadItems(){
  firebase.database().ref('items')
        .orderByChild('title')
        .startAt(_start)
        .endAt(_end)
        .limitToFirst(_n)
        .on("child_added", snapshot=> console.log(snapshot.val()));
  _start += _n;
  _end += _n;
}

回答1:


You're misunderstanding how Firebase queries work. It's easiest to see if you use hard-coded values:

firebase.database().ref('items')
    .orderByChild('title')
    .startAt(0)
    .endAt(14)
    .limitToFirst(15)

There is no item with title=0 or title=14, so the query doesn't match anything.

Firebase Database queries match on the value of the property you order on. So when you order by title the values you specify in startAt and endAt must be titles. E.g.

ref.child('items')
   .orderByChild('title')
   .startAt("Product 1")
   .endAt("Product 1")
   .limitToFirst(15)
   .on("child_added", function(snapshot) { console.log(snapshot.val()); });

See for the working sample of this: http://jsbin.com/hamezu/edit?js,console

To implement pagination, you'll have to remember the last item of the previous page and pass that in to the next call: startAt(titleOfLastItemOnPreviousPage, keyOfLastItemOnPreviousPage).



来源:https://stackoverflow.com/questions/43963770/firebase-lazy-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!