1

I am having trouble returning an array of objects in desc order from firebase and javascript with react native. I am essentially "joining" two firebase parents and then pushing them into an array.

async loadChats(userId){

 this.chatIdRef = firebase.database().ref("members");
 this.chatIdRef.off();
 this.chatsRef = firebase.database().ref("chats");
 this.chatsRef.off();

 items = [];
 this.chatIdRef.child(userId).on('child_added', snap => {
 this.chatsRef.child(snap.key).startAt().on('value', snapshot => {

    items.push({
      receiverId: snap.val().userId,
      timeStamp: snapshot.val().createdAt,
      name: snap.val().userName,
      key: snapshot.key
    });

  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(items)
  });

  });
 });
}

I have tried using "orderByChild('createdAt')" in my query but no luck.

Community
  • 1
  • 1
Neil
  • 95
  • 3
  • 9
  • 1
    Firebase Database queries return items in ascending order. There is no built-in operator to reverse that order. You can either reverse the results client-side, or add a property with an inverted value (i.e. -1 * timestamp) to your data model. – Frank van Puffelen Jul 06 '17 at 17:54
  • Previous questions covering this: https://stackoverflow.com/q/25611356, https://stackoverflow.com/q/38548406, https://stackoverflow.com/q/34156996, or any of [the results in this list](http://stackoverflow.com/search?q=%5Bfirebase-database%5D+descending). – Frank van Puffelen Jul 06 '17 at 17:59
  • Using a negative timestamp works perfectly. Thanks – Neil Jul 09 '17 at 00:08
  • I used .reverse to order the elements from newest to oldest. – programandoconro Nov 17 '19 at 14:56

1 Answers1

0

From the Firebase docs, queries with orderByChild return lists in the following order :-

Children with a null value for the specified child key come first.

Children with a value of false for the specified child key come next. If multiple children have a value of false, they are sorted lexicographically by key.

Children with a value of true for the specified child key come next. If multiple children have a value of true, they are sorted lexicographically by key.

Children with a numeric value come next, sorted in ascending order. If multiple children have the same numerical value for the specified child node, they are sorted by key.

Strings come after numbers and are sorted lexicographically in ascending order. If multiple children have the same value for the specified child node, they are ordered lexicographically by key.

Objects come last and are sorted lexicographically by key in ascending order.

So, from the above, please note that when your data has numerical values, it is returned in ascending order. Now that you know the order in which the data will be retrieved, you can just make changes to your client app to show the data in reverse ( in descending order ). Maybe reverse your list or something similar?

Community
  • 1
  • 1
Rohan Stark
  • 2,346
  • 9
  • 16