Skip to content

Instantly share code, notes, and snippets.

@allyraza
Last active June 15, 2016 10:30
Show Gist options
  • Save allyraza/1c9000b8fd533297fd2e to your computer and use it in GitHub Desktop.
Save allyraza/1c9000b8fd533297fd2e to your computer and use it in GitHub Desktop.
react chat component
// App Components
class App extends React.Component {
constructor(){
super();
this.state = {activeRoom: "general", messages: [], channel: socket.channel("rooms:general")};
}
componentDidMount() {
this.configureChannel(this.state.channel);
}
configureChannel(channel) {
channel.on("message_new", payload => {
this.setState({messages: this.state.messages.concat([payload.text])});
});
channel.on("user_joined", payload => {
this.setState({messages: this.state.messages.concat([payload.text])});
});
// hm...
channel.join()
.receive("ok", () => { console.log("Successfully joined the " + this.state.activeRoom + " chat room.")})
.receive("error", () => { console.log("Unable to join the " + this.state.activeRoom + " chat room.")});
}
onClickRoom = (room) => {
let channel = socket.channel("rooms:" + room);
this.setState({activeRoom: room, messages: [], channel: channel});
this.configureChannel(channel);
}
onSubmitMessage = (message) => {
this.state.channel.push("message_new", {text: message});
}
render() {
return (
<div>
<RoomList rooms={rooms} onClick={this.onClickRoom}/>
<ActiveRoom room={this.state.activeRoom} messages={this.state.messages} onSubmit={this.onSubmitMessage}/>
</div>
);
}
}
export default App;
// console logs
push: rooms:general phx_join (1) Object {}
app.js?vsn=67D445C:21118 transport: connected to ws://localhost:4000/socket/websocket?token=undefined&vsn=1.0.0 WebSocket {CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3}
app.js?vsn=67D445C:21118 receive: ok rooms:general phx_reply (1) Object {status: "ok", response: Object}
app.js?vsn=67D445C:23211 Successfully joined the general chat room.
app.js?vsn=67D445C:21118 receive: rooms:general user_joined Object {text: "new user joined!"}
app.js?vsn=67D445C:21118 receive: connected rooms:general join Object {status: "connected"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment