feat: socket hooks

This commit is contained in:
cha0s 2022-03-14 13:23:51 -05:00
parent fb988c9c82
commit 090762fd5c
5 changed files with 25 additions and 0 deletions

View File

@ -29,6 +29,7 @@
],
"dependencies": {
"@flecks/core": "^1.3.0",
"@flecks/react": "^1.3.0",
"msgpack-lite": "^0.1.26",
"proxy-addr": "^2.0.6",
"schemapack": "^1.4.2",

View File

@ -0,0 +1,2 @@
export {default as useSocket} from './use-socket';
export {default as useSocketPacket} from './use-socket-packet';

View File

@ -0,0 +1,14 @@
import {useEffect} from '@flecks/react';
import useSocket from './use-socket';
export default function useSocketPacket(fn, deps = []) {
const socket = useSocket();
useEffect(() => {
socket.on('packet', fn);
socket.on('disconnect', () => socket.off('packet', fn));
socket.on('reconnect', () => socket.on('packet', fn));
return () => socket.off('packet', fn);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps.concat([fn, socket]));
}

View File

@ -0,0 +1,7 @@
import {useFlecks} from '@flecks/react';
export default function useSocket() {
const flecks = useFlecks();
const sock = flecks.get('$flecks/socket.socket');
return sock;
}

View File

@ -6,6 +6,7 @@ import Redirect from './packet/redirect';
import Refresh from './packet/refresh';
export {default as normalize} from './normalize';
export * from './hooks';
export {default as Packet, Packer, ValidationError} from './packet';
export default {