Zubair Amjad
Zubair Amjad

Reputation: 761

Firebase most recent entries show last

I am trying to sort entries in my firebase by the most recent entry showing up as the first entry. I keep running into the issue that the most recent entry shows up last.

I am trying to sort by time as well as this is how it is set up in my databases: enter image description here

I am also doing this in my code

 completed.child(user.uid).orderByValue("time")

I was wondering where I was going wrong

This is how it shows up in my app: strong text

Upvotes: 1

Views: 310

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599686

There are quite a few problems with your code, so I'll try to address them in turn.


To order by a child property, use orderByChild

You're calling orderByValue("time"), but if you check the documentation you'll note that orderByValue() takes no parameters. If you want to order on the value of a child property, you should call orderByChild("time").


Use a time format that allows sorting them

Your current time format is not suited for sorting it. The problem is that your lexicographical sort order doesn't match with the chronological sort order you want. More simply put, this is the sort order you'll get (but not want):

  • "6:26AM"
  • "6:26PM"
  • "6:27AM"

To get the result you want, use a string format that allows the sorting. For example, use 24 hour/military notation with 0-padding:

  • "06:26"
  • "06:27"
  • "18:26"

You could also store a numerical value, for example: the number of minutes since midnight:

  • (( 6 * 60) + 26) = 386
  • (( 6 * 60) + 27) = 387
  • ((18 * 60) + 26) = 1106

Firebase always returns in ascending order

Firebase always returns results in ascending order. I'll recommend reading a few relevant questions, but you have two options here:

  1. Reverse the results client-side. This is often the simplest, as you're usually dealing with relatively a small result set.
  2. Store an inverted value in the database for sorting.

This last one is typically easiest if you use a numerical value, like the number of minutes since midnight that we used above. If we store -1 * this value, we can then sort on that to get the results in reverse.

  • -1 * (( 6 * 60) + 26) = -386
  • -1 * (( 6 * 60) + 27) = -387
  • -1 * ((18 * 60) + 26) = -1106

Upvotes: 1

Related Questions