Skip to content

Instantly share code, notes, and snippets.

@LuffyAnshul
Last active January 17, 2021 06:48
Show Gist options
  • Save LuffyAnshul/5d8478bcf9939706e759dc4d4cad01a1 to your computer and use it in GitHub Desktop.
Save LuffyAnshul/5d8478bcf9939706e759dc4d4cad01a1 to your computer and use it in GitHub Desktop.
Private Chat React Native; what is happening is useEffect
useEffect(() => {
readUser();
const unsubscribe = chatsRef.onSnapshot((querySnapshot) => {
const messagesFirestore = querySnapshot
.docChanges()
.filter(({ type }) => type === 'added')
.map(({ doc }) => {
const message = doc.data();
return {
...message,
createdAt: message.createdAt.toDate(),
};
})
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
appendMessages(messagesFirestore);
});
return () => unsubscribe();
}, []);
const appendMessages = useCallback(
(messages) => {
setMessages((previousMessages) =>
GiftedChat.append(previousMessages, messages)
);
},
[messages]
);
async function readUser() {
const user = await AsyncStorage.getItem('user');
if (user) {
setUser(JSON.parse(user));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment