Last active
August 19, 2018 22:54
-
-
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
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 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