Home > Web Front-end > JS Tutorial > How to Display Firebase Posts in Descending Order?

How to Display Firebase Posts in Descending Order?

Susan Sarandon
Release: 2024-11-07 12:45:03
Original
633 people have browsed it

How to Display Firebase Posts in Descending Order?

Displaying Posts in Descending Posted Order with Firebase

As you're working with Firebase to enable user commenting through push, you're seeking a way to display the retrieved data in descending posted order, reversing the default oldest-to-newest ordering.

Firebase offers two methods for retrieving child nodes: by name and by priority. The default order is lexicographic by name, which ensures chronological ordering when using push() to generate child names.

Solution 1: Inverting Timestamp as Priority

To achieve the desired order, you can add a child property with an inverted timestamp and order on that instead:

<code class="python">var ref = new Firebase('https://your.firebaseio.com/sell');
var item = ref.push();
item.setWithPriority(yourObject, 0 - Date.now());</code>
Copy after login

Solution 2: Reading in Ascending Order and Inverting on Client

Alternatively, you can retrieve the children in ascending order and invert them on the client side. However, you'll need to modify the retrieval query as follows:

<code class="python">fbl.child('sell').startAt().limitToLast(20).on('child_added', function(fbdata) {
  console.log(fbdata.exportVal());
})</code>
Copy after login

Using on('child_added') ensures that the last few children added are returned in reverse chronological order. In contrast, on('value') returns them in name order.

Update:

Note that Firebase now allows ordering by any child or by value, providing more flexibility in how you can sort your data.

The above is the detailed content of How to Display Firebase Posts in Descending Order?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template