Firebase orderByChild on React Native

问题: I am having an issue with ordering of a list on android. The database ref items/ looks like this below: { "11" : { "date" : "2018-11-18 10:07:00", "le...

问题:

I am having an issue with ordering of a list on android. The database ref items/ looks like this below:

{
    "11" : {
        "date" : "2018-11-18 10:07:00",
        "letter" : "F",
        "number" : 11
    },
    "12" : {
        "date" : "2018-11-01 14:41:00",
        "letter" : "B",
        "number" : 12
    },
    "13" : {
        "date" : "2018-11-13 14:00:00",
        "letter" : "C",
        "number" : 13
    },
    "14" : {
        "date" : "2019-04-22 22:15:30",
        "letter" : "D",
        "number" : 14
    },
    "15" : {
        "date" : "2019-04-22 20:33:00",
        "letter" : "H",
        "number" : 15
    },
    "16" : {
        "date" : "2019-04-22 19:30:00",
        "letter" : "J",
        "number" : 16
    },
    "17" : {
        "date" : "2019-04-25 13:10:00",
        "letter" : "G",
        "number" : 17
    },
    "18" : {
        "date" : "2019-04-25 18:00:00",
        "letter" : "E",
        "number" : 18
    },
    "19" : {
        "date" : "2019-04-25 13:00:00",
        "letter" : "I",
        "number" : 19
    },
    "20" : {
        "date" : "2019-04-28 12:30:00",
        "letter" : "A",
        "number" : 20
    }
}

I am querying it as below expecting the results to be ordered by the 'letter' key:

firebase.database().ref('items/').orderByChild('letter').on('value', snapshot => {
    let items = snapshot.val()
    Object.values(items).map(i => console.log(i.number, i.letter, i.date))
})

But I get the results logged as below:

11 F 2018-11-18 10:07:00
12 B 2018-11-01 14:41:00
13 C 2018-11-13 14:00:00
14 D 2019-04-22 22:15:30
15 H 2019-04-22 20:33:00
16 J 2019-04-22 19:30:00
17 G 2019-04-25 13:10:00
18 E 2019-04-25 18:00:00
19 I 2019-04-25 13:00:00
20 A 2019-04-28 12:30:00

Obviously the orderByChild('letter') is not getting applied. What could I be missing?


回答1:

Apparently there is an issue with how objects are handled in JavaScript, that's why there is a snapshot.forEach method for one to use instead of the Object.values(items).map that I am using. My listener should look something like this:

firebase.database().ref('items/').orderByChild('letter').on('value', snapshot => {
    snapshot.forEach(c => { i = c.val(); console.log(i.number, i.letter, i.date) })
})

Because of the way JavaScript objects work, the ordering of data in the JavaScript object returned by val() is not guaranteed to match the ordering on the server nor the ordering of child_added events. That is where forEach() comes in handy. It guarantees the children of a DataSnapshot will be iterated in their query order.

https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#forEach

  • 发表于 2019-03-09 15:00
  • 阅读 ( 188 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除