Created
May 21, 2020 18:44
-
-
Save Marxpark/28aa7ea870259a3e5eac7ef6c2cce1dc to your computer and use it in GitHub Desktop.
component wrapper withSocket
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 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