2

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()))
            }
        });
    }, [])

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

This is working and doing the job but its crashes after each msg is sent ERROR : TypeError: Cannot read properties of null (reading 'toMillis')
@ArnabKumar that means createdAt field is missing from the document. Are you sure that field is present ? Also just .sort((a, b) => a.createdAt - b.createdAt) should do it iirc.
Yes 100% sure it is present
@ArnabKumar can you console.log(snapshot.data()) before this sort function and share the output to ensure that?
its working after removing the .toMilis()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.