-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathChat.tsx
111 lines (106 loc) · 2.39 KB
/
Chat.tsx
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import React, { useState, useMemo, useEffect } from "react";
import {
View,
Text,
ScrollView,
TextInput,
KeyboardAvoidingView
} from "react-native";
import gql from "graphql-tag";
import { useQuery, useMutation, useSubscription } from "react-apollo-hooks";
import withSuspense from "./withSuspense";
const GET_MESSAGES = gql`
query messages {
messages {
id
text
}
}
`;
const SEND_MESSAGE = gql`
mutation sendMessage($text: String!) {
sendMessage(text: $text) {
id
text
}
}
`;
const NEW_MESSAGE = gql`
subscription newMessage {
newMessage {
id
text
}
}
`;
function Chat() {
const [message, setMessage] = useState("");
const sendMessageMutation = useMutation(SEND_MESSAGE, {
variables: {
text: message
}
});
const {
data: { messages: oldMessages },
error
} = useQuery(GET_MESSAGES, {
suspend: true
});
const { data } = useSubscription(NEW_MESSAGE);
const [messages, setMessages] = useState(oldMessages || []);
const handleNewMessage = () => {
if (data !== undefined) {
const { newMessage } = data;
setMessages(previous => [...previous, newMessage]);
}
};
useEffect(() => {
handleNewMessage();
}, [data]);
const onChangeText = text => setMessage(text);
const onSubmit = async () => {
if (message === "") {
return;
}
try {
await sendMessageMutation();
setMessage("");
} catch (e) {
console.log(e);
}
};
return (
<KeyboardAvoidingView style={{ flex: 1 }} enabled behavior="padding">
<ScrollView
contentContainerStyle={{
paddingVertical: 50,
flex: 1,
justifyContent: "flex-end",
alignItems: "center"
}}
>
{messages.map(m => (
<View key={m.id} style={{ marginBottom: 10 }}>
<Text>{m.text}</Text>
</View>
))}
<TextInput
placeholder="Type a message"
style={{
marginTop: 50,
width: "90%",
borderRadius: 10,
paddingVertical: 15,
paddingHorizontal: 10,
backgroundColor: "#f2f2f2"
}}
returnKeyType="send"
value={message}
onChangeText={onChangeText}
onSubmitEditing={onSubmit}
/>
</ScrollView>
</KeyboardAvoidingView>
);
}
export default withSuspense(Chat);