Last active
July 11, 2019 04:17
-
-
Save iamronsuez/eaf8525a8167c797a80f9f027a5e5c5f to your computer and use it in GitHub Desktop.
Simple WebSocket React
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 React from 'react' | |
import './App.css' | |
import socketIOClient from 'socket.io-client' | |
class App extends React.Component { | |
state = { | |
endpoint: 'https://ddf34c69.ngrok.io/', | |
ts: new Date(), | |
data: {} | |
} | |
componentDidMount () { | |
const socket = socketIOClient(this.state.endpoint) | |
socket.on('Holis', data => this.setState({data: Object.assign({}, data, this.state.data), ts: new Date()}, () => console.log('updated'))) | |
} | |
_getTs = (ts) => `${ts.getHours()}:${ts.getMinutes()}:${ts.getSeconds()}` | |
_getInfoBox = ({key, value: {temperature, datetime}}) => { | |
return ( | |
<div key={key} style={{height: 150, width: 150, backgroundColor: 'blue', color: 'white', margin: '0px 10px', display: 'flex', flexDirection: 'column'}}> | |
<p>{key}</p> | |
<p>{temperature}</p> | |
<span>{this._getTs(new Date(datetime))}</span> | |
</div> | |
) | |
} | |
_sortElements = (a,b) => { | |
const keyA= a.key.toLowerCase(), keyB=b.key.toLowerCase() | |
if (keyA < keyB) return -1 | |
if (keyA > keyB) return 1 | |
return 0 | |
} | |
render () { | |
const {ts, data} = this.state | |
return ( | |
<div className='App'> | |
<header> | |
<h4> | |
{this._getTs(ts)} | |
</h4> | |
</header> | |
<div style={{display: 'flex', justifyContent: 'center'}}> | |
<div style={{display: 'flex'}}> | |
{Object.entries(data).map(([key, value]) => ({key, value})).sort(this._sortElements).map(this._getInfoBox)} | |
</div> | |
</div> | |
</div> | |
) | |
} | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment