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
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);
}