Last active
February 28, 2019 00:02
-
-
Save emilwidlund/64de987c6d565fa1e180f3ef7c99ea33 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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