Currently, I'm in the process of developing a chat application using Firestore. The approach involves utilizing Flatlist and querying with onSnapshot() to provide real-time updates for both sender and receiver.
Here's an example of my query:
const ChatMessages = useCallback(() => {
privateMessage
.doc(chatId)
.collection('messages')
.orderBy('createdAt', 'asc')
.onSnapshot((querySnapshot) => {
const messageList = [];
querySnapshot.forEach((doc) => {
messageList.push(doc.data());
})
setMessages(messageList);
}, error => {
console.log(error)
})
}, [chatId])
In the sample flatlist, I include the user's display name, message content, and the timestamp when the message was created:
<FlatList
data={messages}
keyExtractor={(item, index) => String(index)}
removeClippedSubviews={false}
renderItem={({ item }) => (
<View>
<Text style={chatstyle.pmdate}>
{item.createdAt.toDate().toDateString()}
</Text>
<Text>
{item.displayName}
</Text>
<Text>
{item.message}
</Text>
</View>
)}
/>
Although I aim to show the date and time stamp alongside the message, encountering an issue where the line {item.createdAt.toDate().toDateString()} throws a null object error while using onSnapshot(). Any advice on the correct method to display the timestamp through onSnapshot() without errors?
Your input would be greatly appreciated!