chore: from flecks-vite
This commit is contained in:
parent
9872cbb423
commit
0e8e58b365
29
app/react/hooks/use-web-socket.js
Normal file
29
app/react/hooks/use-web-socket.js
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user