-
Notifications
You must be signed in to change notification settings - Fork 1
/
clientChat.js
105 lines (97 loc) · 2.54 KB
/
clientChat.js
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
import SocketIOClient from 'socket.io-client';
import React from 'react';
import { Col, Row, Grid } from 'react-native-easy-grid';
import { StyleSheet } from 'react-native';
import {
Container,
Header,
Title,
Content,
Card,
CardItem,
Body,
Item,
Input,
Button,
Spinner,
Text } from 'native-base';
export default class Client extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [],
userID: null,
myName: props.userName,
text: '',
roomID: 0,
category: props.category
}
this.receiveMessage = this.receiveMessage.bind(this);
this.sendMessage = this.sendMessage.bind(this);
this.socket = SocketIOClient('http://e99bfd18.ngrok.io', { transports: ['websocket'] });
this.getMessages = this.getMessages.bind(this)
}
componentWillMount () {
this.getMessages();
}
getMessages () {
fetch(`http://e99bfd18.ngrok.io/rooms/${this.state.category}/`)
.then((response) => response.json())
.then((responseJSON) => this.setState({ messages: responseJSON.messages }));
}
sendMessage (message) {
if (message.length === 0) {
return;
}
const messageBody = {
'text': message,
'user': this.state.myName,
'room': this.state.roomID,
'category': this.state.category
}
this.socket.emit("json", messageBody);
this.socket.on("json", this.receiveMessage);
console.log(this.state.messages);
this.setState({text: ''});
}
receiveMessage(msg){
this.setState({messages : msg});
}
render (){
return (
<Card>
<Card>
{
this.state.messages.length > 0 ? this.state.messages.map((message) =>
<Card>
<CardItem>
<Body>
<Text>
{message.body}
</Text>
</Body>
</CardItem>
</Card>
) : <Card />
}
</Card>
<Card>
<Grid>
<Col size={80}>
<Item>
<Input
placeholder="Enter text here."
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
</Item>
</Col>
<Col size={20}>
<Button danger onPress={()=> {this.sendMessage(this.state.text);}}><Text>Enter</Text></Button>
</Col>
</Grid>
</Card>
</Card>
);
}
}