chore: from flecks-vite

This commit is contained in:
cha0s 2024-11-04 22:12:58 -06:00
parent 9872cbb423
commit 0e8e58b365

View File

@ -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;
}