how to use orderBy() in onSnapshot() so I can order the documents on the basis of the timestamp?

Viewed 908

So basically please tell me how I should implement the orderBy() function of firestore in onSnapshot() in React. Please help me, guys. I really need your help. If your answering my question please share this code with the orderBy() function implement in it. Here is my code -

onSnapshot(collection(db, "messages"), (snapshot) => {
setMessages(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id})))
 })

and I have returned this

<div className="chat-app">
    {messages && messages.map((msg) => {
      return (
        <div key={msg.id} className="message">
          <img className="img" src={msg.image}></img>
          <div className="msg">{msg.message}</div>
        </div> 
      )
    } )}
1 Answers

Instead of a "simple" CollectionReference, you can pass a Query to the onSnaphot() Function, as follows. You'll find more details in the Firestore documentation.

import { ..., collection, query, orderBy} from "firebase/firestore";  

const q = query(collection(db, "messages"), orderBy("xyz"));
onSnapshot(q, (snapshot) => {
    setMessages(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
})

Note: Actually a CollectionReference extends a Query.

Related