Skip to content

Instantly share code, notes, and snippets.

@spencerfeng
Last active August 19, 2018 22:54
Show Gist options
  • Save spencerfeng/5d1274d77a8c0d9dbdf75f8b2ec8dcac to your computer and use it in GitHub Desktop.
Save spencerfeng/5d1274d77a8c0d9dbdf75f8b2ec8dcac to your computer and use it in GitHub Desktop.
For tutorial: How to use a single instance of Socket.IO in your React app
import React, { Component } from 'react'
import SocketContext from './socket-context'
import axios from 'axios'
class YourDeeplyNestedComponent extends Component {
componentDidMount() {
axios.post('/api/messages', {
message: 'This is a new message'
})
.then(response => {
this.props.socket.emit('new-message-added', response.data.newMessage)
})
}
render() {
...
}
}
const YourDeeplyNestedComponentWithSocket = props => (
<SocketContext.Consumer>
{socket => <YourDeeplyNestedComponent {...props} socket={socket} />}
</SocketContext.Consumer>
)
export default YourDeeplyNestedComponentWithSocket
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment