Skip to content

Instantly share code, notes, and snippets.

@keithweaver
Created March 28, 2018 11:07
Show Gist options
  • Save keithweaver/06fb43df85f956eccaa7ef18b277ed00 to your computer and use it in GitHub Desktop.
Save keithweaver/06fb43df85f956eccaa7ef18b277ed00 to your computer and use it in GitHub Desktop.
Socket.io Medium Post
import React, { Component } from 'react';
import 'whatwg-fetch';
import openSocket from 'socket.io-client';
const socket = openSocket('http://localhost:8000');
class Home extends Component {
constructor(props) {
super(props);
this.state = {
counters: []
};
this.newCounter = this.newCounter.bind(this);
this.incrementCounter = this.incrementCounter.bind(this);
this.decrementCounter = this.decrementCounter.bind(this);
this.deleteCounter = this.deleteCounter.bind(this);
this._modifyCounter = this._modifyCounter.bind(this);
this.sendSocketIO = this.sendSocketIO.bind(this);
}
componentDidMount() {
fetch('/api/counters')
.then(res => res.json())
.then(json => {
this.setState({
counters: json
});
});
}
newCounter() {
fetch('/api/counters', { method: 'POST' })
.then(res => res.json())
.then(json => {
let data = this.state.counters;
data.push(json);
this.setState({
counters: data
});
});
}
incrementCounter(index) {
const id = this.state.counters[index]._id;
fetch(`/api/counters/${id}/increment`, { method: 'PUT' })
.then(res => res.json())
.then(json => {
this._modifyCounter(index, json);
});
}
decrementCounter(index) {
const id = this.state.counters[index]._id;
fetch(`/api/counters/${id}/decrement`, { method: 'PUT' })
.then(res => res.json())
.then(json => {
this._modifyCounter(index, json);
});
}
deleteCounter(index) {
const id = this.state.counters[index]._id;
fetch(`/api/counters/${id}`, { method: 'DELETE' })
.then(_ => {
this._modifyCounter(index, null);
});
}
_modifyCounter(index, data) {
let prevData = this.state.counters;
if (data) {
prevData[index] = data;
} else {
prevData.splice(index, 1);
}
this.setState({
counters: prevData
});
}
sendSocketIO() {
socket.emit('chat message', 'demo');
}
render() {
return (
<div>
<p>Counters:</p>
<ul>
{ this.state.counters.map((counter, i) => (
<li key={i}>
<span>{counter.count} </span>
<button onClick={() => this.incrementCounter(i)}>+</button>
<button onClick={() => this.decrementCounter(i)}>-</button>
<button onClick={() => this.deleteCounter(i)}>x</button>
</li>
)) }
</ul>
<button onClick={this.newCounter}>New counter</button>
<div>
<button onClick={this.sendSocketIO}>Send Socket.io</button>
</div>
</div>
);
}
}
export default Home;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment