Home > database >  How to sort my array of objects based on firebase Timestamp
How to sort my array of objects based on firebase Timestamp

Time:03-27

I need my messages should be ordered based on timestamp ("createdAt" is the name of filed) i can do it in earlier versions of firebase but cant fig out how to do it in firebase v9

DATA STRUCTURE ON FIRESTORE

SEE IMAGE HERE

const [messages, setMessages] = useState([])
    useEffect(() => {

        const unsub = onSnapshot(doc(db, "messages", state.id), (snapshot) => {
            if(snapshot.data()){
                console.log(123,Object.values(snapshot.data()))
                setMessages(Object.values(snapshot.data()))
            }
        });
    }, [])

CodePudding user response:

What you have in your document is not an array. They are just fields with random IDs. You can sort them using .sort() as shown below:

if (snapshot.data()) {
  const sortedMessages = Object.values(snapshot.data()).sort((a, b) => a.createdAt.toMillis() - b.createdAt.toMillis())

  setMessages(sortedMessages);
}
  • Related