/
index.js
63 lines (55 loc) · 1.86 KB
/
index.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
import React from "react";
import ReactDom from "react-dom";
import SockJsClient from "react-stomp";
import UsernameGenerator from "username-generator";
import Fetch from "json-fetch";
import { TalkBox } from "react-talk";
const randomstring = require("randomstring");
class App extends React.Component {
constructor(props) {
super(props);
// randomUserId is used to emulate a unique user id for this demo usage
this.randomUserName = UsernameGenerator.generateUsername("-");
this.randomUserId = randomstring.generate();
this.state = {
clientConnected: false,
messages: []
};
}
onMessageReceive = (msg, topic) => {
this.setState(prevState => ({
messages: [...prevState.messages, msg]
}));
}
sendMessage = (msg, selfMsg) => {
try {
this.clientRef.sendMessage("/app/all", JSON.stringify(selfMsg));
return true;
} catch(e) {
return false;
}
}
componentWillMount() {
Fetch("/history", {
method: "GET"
}).then((response) => {
this.setState({ messages: response.body });
});
}
render() {
const wsSourceUrl = window.location.protocol + "//" + window.location.host + "/handler";
return (
<div>
<TalkBox topic="react-websocket-template" currentUserId={ this.randomUserId }
currentUser={ this.randomUserName } messages={ this.state.messages }
onSendMessage={ this.sendMessage } connected={ this.state.clientConnected }/>
<SockJsClient url={ wsSourceUrl } topics={["/topic/all"]}
onMessage={ this.onMessageReceive } ref={ (client) => { this.clientRef = client }}
onConnect={ () => { this.setState({ clientConnected: true }) } }
onDisconnect={ () => { this.setState({ clientConnected: false }) } }
debug={ false }/>
</div>
);
}
}
ReactDom.render(<App />, document.getElementById("root"));