-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcode rementnatns.txt
85 lines (77 loc) · 2.02 KB
/
code rementnatns.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import React, {
useState,
useEffect,
useLayoutEffect,
useCallback,
} from "react";
import { TouchableOpacity, Text } from "react-native";
import { GiftedChat } from "react-native-gifted-chat";
import {
collection,
addDoc,
orderBy,
query,
onSnapshot,
} from "firebase/firestore";
import { signOut } from "firebase/auth";
import { auth, database } from "../config/firebase";
//chat useState
export default function Chat_2({ navigation }) {
const [messages, setMessages] = useState([]);
//This code will prevent signedout users from accessing chat without another sign-in.
const onSignOut = () => {
signOut(auth).catch((error) => console.log("Error logging out: ", error));
};
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<TouchableOpacity
style={{
marginRight: 10,
}}
onPress={onSignOut}
>
<Text>Logout</Text>
</TouchableOpacity>
),
});
}, [navigation]);
useLayoutEffect(() => {
const collectionRef = collection(database, "chats");
const q = query(collectionRef, orderBy("createdAt", "desc"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
setMessages(
querySnapshot.docs.map((doc) => ({
_id: doc.data()._id,
createdAt: doc.data().createdAt.toDate(),
text: doc.data().text,
user: doc.data().user,
}))
);
});
return unsubscribe;
});
const onSend = useCallback((messages = []) => {
setMessages((previousMessages) =>
GiftedChat.append(previousMessages, messages)
);
const { _id, createdAt, text, user } = messages[0];
addDoc(collection(database, "chats"), {
_id,
createdAt,
text,
user,
});
}, []);
return (
<GiftedChat
messages={messages}
showAvatarForEveryMessage={true}
onSend={(messages) => onSend(messages)}
user={{
_id: auth?.currentUser?.email,
avatar: "https://i.pravatar.cc/300",
}}
/>
);
}