0

I'm fetch list data on my realtime database in my app on React Native, but i can't sort as i need to.

My code from request is:

const ref = firebase
  .database()
  .ref('name_collection')
  .orderByChild('key');

I need sort the result by field "key" to desc. What is a method indicated to this?

This is example of my data:

{
    "-LyRTCDBTbflu77UpWt5": {
        "key": 1,
        "title": "Loren ipsun dolor"
    },
    "-LyRTJyTdrJ3pLo7FED1": {
        "key": 3,
        "title": "Loren ipsun dolor"
    },
    "-LyRTNZEBEr6-vKOxOOf": {
        "key": 2,
        "title": "Loren ipsun dolor"
    }
}
Daniel
  • 15
  • 1
  • 6
  • I'm not clear what you mean. Are you saying you want to reverse the direction of the sort you see now? That would be a "desc" (descending) sort, not an asc ("ascending") sort. (Realime Database actually can't do this.) – Doug Stevenson Jan 13 '20 at 02:27
  • @DougStevenson sory, i updated my question. I'm need sort my result from 1 to 3. – Daniel Jan 13 '20 at 03:05
  • Well, your keys appear to be strings (they are shown in quotes here - so they are strings), so they won't sort numerically. If you want a numeric sort, the key values should be numbers. – Doug Stevenson Jan 13 '20 at 03:07
  • That's correctly, changed to number, but the result is same. – Daniel Jan 13 '20 at 03:20
  • Query results are always returned in ascending order. If you want them in descending order, you can either reverse the results client side, or store an inverted value in the database (i.e. `"invertedKey": -2`) and sort on that. See https://stackoverflow.com/q/45153297, https://stackoverflow.com/a/44443042 and more from this: https://stackoverflow.com/search?q=%5Bfirebase-realtime-database%5D%5Bjavascript%5D+descending+query – Frank van Puffelen Jan 13 '20 at 03:29

0 Answers0