Skip to content

Instantly share code, notes, and snippets.

@Marxpark
Created May 21, 2020 18:44
Show Gist options
  • Save Marxpark/28aa7ea870259a3e5eac7ef6c2cce1dc to your computer and use it in GitHub Desktop.
Save Marxpark/28aa7ea870259a3e5eac7ef6c2cce1dc to your computer and use it in GitHub Desktop.
component wrapper withSocket
import React from "react"
import socketIOClient from "socket.io-client";
// link should be in environemnt file!
let socket = socketIOClient(process.env.REACT_APP_SOCKET_URL)
// component wrapper that allows us to use socket globaly
function withSocket (WrappedComponent) {
const WithSocket = props => {
// function to subscribe to events
const socketListen = async (queue, callback) => {
socket.on(queue, data => {
callback(data)
})
}
const socketSend = async(queue, data) => {
socket.emit(queue, JSON.stringify(data))
}
return (
<WrappedComponent
{...props}
socketSend={socketSend}
socketListen={socketListen}
/>
)
}
return WithSocket
}
export default withSocket
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment