26 lines
605 B
JavaScript
26 lines
605 B
JavaScript
import {createContext, useContext, useEffect} from 'react';
|
|
|
|
const context = createContext();
|
|
|
|
export default context;
|
|
|
|
export function useClient() {
|
|
return useContext(context);
|
|
}
|
|
|
|
export function usePacket(type, fn, dependencies) {
|
|
const client = useClient();
|
|
useEffect(() => {
|
|
if (!client) {
|
|
return;
|
|
}
|
|
function listener(payload) {
|
|
fn(payload, client);
|
|
}
|
|
client.addPacketListener(type, listener);
|
|
return () => {
|
|
client.removePacketListener(type, listener);
|
|
};
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [client, ...dependencies]);
|
|
} |