Reputation: 169
So in React, I'm reading a firebase real-time database using the "react-firebase-hooks/database"
package.
import { useList } from "react-firebase-hooks/database";
import { db, auth } from "../../firebase";
function GameHistory() {
var dbRef = db.ref("/" + user.uid);
const [snapshots, loading, error] = useList(dbRef);
So basically snapshots variable contains all the firebase realtime database data. Then later in my code I simply map each element of the snapshot array into a component.
Here is the problem, I want to sort my snapshots data in order of the .timestamp
firebase property in my data. I'm not sure how to do this.
I tried to sort the snapshot data when I map it:
snapshots
.sort((a, b) => {
return a.val().timestamp > b.val().timestamp;
})
.map((game, index) => (MORE CODE
But that doesn't work because timestamp is a firebase object, and JavaScript doesn't know what to do with it.
Just to establish more context on the timestamp variable, I defined it as such:
timestamp: firebase.firestore.FieldValue.serverTimestamp()
So is there any way to sort my snapshot data? Or should I use another package? If I should use something else please show code for how you read and sort the realtime db.
Upvotes: 0
Views: 859
Reputation: 598623
You're mixing up two different databases here:
import { useList } from "react-firebase-hooks/database"
and other code are for the Realtime Database.timestamp: firebase.firestore.FieldValue.serverTimestamp()
is for Cloud FirestoreWhile both databases are part of Firebase, they are completely separate and each has their own API.
To write a server-side timestamp to Realtime Database, use:
timestamp: firebase.database.ServerValue.TIMESTAMP
I'd actually also let the database server handle the sorting, instead of doing this in your code, which is done with:
var dbRef = db.ref("/" + user.uid);
const dbQuery = dbRef.orderByChild("timestamp");
const [snapshots, loading, error] = useList(dbQuery);
...
Upvotes: 1