I\'m trying to test out Firebase to allow users to post comments using push
. I want to display the data I retrieve with the following;
fbl.child
I'm using ReactFire for easy Firebase integration.
Basically, it helps me storing the datas into the component state, as an array
. Then, all I have to use is the reverse()
function (read more)
Here is how I achieve this :
import React, { Component, PropTypes } from 'react';
import ReactMixin from 'react-mixin';
import ReactFireMixin from 'reactfire';
import Firebase from '../../../utils/firebaseUtils'; // Firebase.initializeApp(config);
@ReactMixin.decorate(ReactFireMixin)
export default class Add extends Component {
constructor(args) {
super(args);
this.state = {
articles: []
};
}
componentWillMount() {
let ref = Firebase.database().ref('articles').orderByChild('insertDate').limitToLast(10);
this.bindAsArray(ref, 'articles'); // bind retrieved data to this.state.articles
}
render() {
return (
<div>
{
this.state.articles.reverse().map(function(article) {
return <div>{article.title}</div>
})
}
</div>
);
}
}
For me it was limitToLast
that worked. I also found out that limitLast
is NOT a function:)
const query = messagesRef.orderBy('createdAt', 'asc').limitToLast(25);
The above is what worked for me.
Someone has pointed out that there are 2 ways to do this:
The easiest way that I have found to do this is to use option 1, but through a LinkedList
. I just append each of the objects to the front of the stack. It is flexible enough to still allow the list to be used in a ListView
or RecyclerView
. This way even though they come in order oldest to newest, you can still view, or retrieve, newest to oldest.
myarray.reverse(); or this.myitems = items.map(item => item).reverse();
To add to Dave Vávra's answer, I use a negative timestamp as my sort_key
like so
Setting
const timestamp = new Date().getTime();
const data = {
name: 'John Doe',
city: 'New York',
sort_key: timestamp * -1 // Gets the negative value of the timestamp
}
Getting
const ref = firebase.database().ref('business-images').child(id);
const query = ref.orderByChild('sort_key');
return $firebaseArray(query); // AngularFire function
This fetches all objects from newest to oldest. You can also $indexOn
the sortKey
to make it run even faster
You can add a column named orderColumn where you save time as
Long refrenceTime = "large future time";
Long currentTime = "currentTime";
Long order = refrenceTime - currentTime;
now save Long order in column named orderColumn and when you retrieve data as orderBy(orderColumn) you will get what you need.