From 0e8e58b365d3be1a9a99d9c313fa5d8c79998bfd Mon Sep 17 00:00:00 2001 From: cha0s Date: Mon, 4 Nov 2024 22:12:58 -0600 Subject: [PATCH] chore: from flecks-vite --- app/react/hooks/use-web-socket.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 app/react/hooks/use-web-socket.js diff --git a/app/react/hooks/use-web-socket.js b/app/react/hooks/use-web-socket.js new file mode 100644 index 0000000..4a0bff6 --- /dev/null +++ b/app/react/hooks/use-web-socket.js @@ -0,0 +1,29 @@ +import {useEffect, useState} from 'react'; + +export function useWebSocket(path, {host, schema} = {}) { + const [socket, setSocket] = useState(); + useEffect(() => { + async function connect() { + const socket = new WebSocket(`${schema || ''}//${host || location.host}${path || '/'}`); + socket.addEventListener('open', () => { + setSocket(socket); + }); + socket.addEventListener('close', ({reason}) => { + if ('hmr' === reason) { + connect(); + } + setSocket(undefined); + }); + } + connect(); + return () => { + setSocket((socket) => { + if (socket) { + socket.close(); + } + return undefined; + }); + } + }, [path, host, schema]); + return socket; +} \ No newline at end of file