Created
January 30, 2019 11:45
-
-
Save herbert1228/83d6b0a39ef1fef7aa0bfefe2fa76ade to your computer and use it in GitHub Desktop.
This file contains 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 React, { Component } from 'react'; | |
import {connection} from './interface/connection' | |
export default class App extends React.Component { | |
state = { | |
counter: 0 | |
} | |
componentDidMount() { | |
connection.connect("ws://localhost:8500") | |
// Anyone who listen to the following events can trigger the handleMessageFromServer callbacks | |
// Cast and Listen may not be performed by the same client | |
connection.addListener("add", this.handleAddMessageFromServer) //receive from server | |
connection.addListener("substract", this.handleSubstractMessageFromServer) //receive from server | |
} | |
handleAddMessageFromServer = (result) => { //receive from server and update | |
this.setState({counter: result}) | |
} | |
handleSubstractMessageFromServer = (result) => { //receive from server and update | |
this.setState({counter: result}) | |
} | |
handleAddCast = () => { //send to server | |
connection.cast("add", 1) | |
} | |
handleSubstractCast = () => { //send to server | |
connection.cast("substract", 1) | |
} | |
render() { | |
return ( | |
<div> | |
<button onClick={this.handleAddCast}>+</button> | |
<h3>{this.state.counter}</h3> | |
<button onClick={this.handleSubstractCast}>-</button> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment