Skip to content

Instantly share code, notes, and snippets.

@emilwidlund
Last active February 28, 2019 00:02
Show Gist options
  • Save emilwidlund/64de987c6d565fa1e180f3ef7c99ea33 to your computer and use it in GitHub Desktop.
Save emilwidlund/64de987c6d565fa1e180f3ef7c99ea33 to your computer and use it in GitHub Desktop.
import * as React from "react";
interface Payload {
text: string;
timestamp: number;
}
interface ChatProps {
}
interface ChatState {
messages: Payload[];
}
export class Chat extends React.Component<ChatProps, ChatState> {
ws: WebSocket = new WebSocket('ws://localhost:8081');
state: ChatState = {
messages: []
}
componentWillMount() {
this.ws.onopen = () => {
console.log('Connection to chat server is now open');
}
this.ws.onclose = () => {
console.log('Connection to chat server is now closed');
}
this.ws.onmessage = (event) => {
const payload = JSON.parse(event.data);
console.log(payload);
this._renderMessage(payload);
}
}
componentWillUnmount() {
this.ws.close();
}
_renderMessage(message: Payload) {
this.setState({
messages: [...this.state.messages, message]
});
}
_sendMessage() {
const payload: Payload = {
text: 'This is a simple message!',
timestamp: Date.now()
}
this.ws.send(JSON.stringify(payload));
}
render() {
return (
<div>
{
this.state.messages.map((message: Payload, i: number) => (
<div key={i}>
<h3 style={{marginBottom: 8}}>{message.text}</h3>
<span>{new Date(message.timestamp).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })}</span>
</div>
))
}
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment