Last active
April 17, 2020 09:05
-
-
Save reecelucas/e3aef5e2e17255464bdcd8f670f9d2f1 to your computer and use it in GitHub Desktop.
React hook to provide a declarative wrapper around the WebSockets API
This file contains hidden or 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 { useEffect, useRef } from 'react' | |
const isFunction = fn => typeof fn === 'function'; | |
const connectionIsOpen = ws => ws && ws.readyState === WebSocket.OPEN; | |
/** | |
* Usage: | |
* const { webSocket, sendMessage, closeConnection } = useWebSocket({ | |
* url: 'wss://echo.websocket.org/', | |
* onOpen: useCallback(event => { | |
* console.log('Connection opened: ', event); | |
* }, []), | |
* onClose: useCallback(event => { | |
* console.log('Connection closed: ', event); | |
* }, []), | |
* onError: useCallback(event => { | |
* console.log('Connection error: ', event); | |
* }, []), | |
* onMessage: useCallback(event => { | |
* console.log('Message received: ', event); | |
* }, []) | |
* }); | |
* | |
* sendMessage('Hello from the client!'); | |
*/ | |
const useWebSocket = ({ url, onOpen, onClose, onMessage, onError }) => { | |
let socket = useRef(); | |
useEffect(() => { | |
socket.current = new WebSocket(url); | |
socket.current.onopen = event => { | |
if (isFunction(onOpen)) { | |
onOpen(event); | |
} | |
}; | |
socket.current.onclose = event => { | |
if (isFunction(onClose)) { | |
onClose(event); | |
} | |
}; | |
socket.current.onmessage = event => { | |
if (isFunction(onMessage)) { | |
onMessage(event); | |
} | |
}; | |
socket.current.onerror = event => { | |
if (isFunction(onError)) { | |
onError(event); | |
} | |
}; | |
}, [url, onOpen, onClose, onMessage, onError]); | |
return { | |
webSocket: socket.current, | |
sendMessage: data => { | |
if (connectionIsOpen(socket.current)) { | |
try { | |
socket.current.send(JSON.stringify(data)); | |
} catch (error) { | |
throw new Error(error); | |
} | |
} | |
}, | |
closeConnection: () => { | |
if (connectionIsOpen(socket.current)) { | |
socket.current.close(); | |
} | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment