@lobstar/preact
Version:
A collection of Preact hooks to use Lobstar library for network and lobby management for multiplayer web games
44 lines (43 loc) • 1.57 kB
JavaScript
import { useEffect, useRef } from "preact/hooks";
/**
* Hook to handle game-specific events
*/
export function useGameEvents(session, onMessage, onError, onKicked) {
const customMessageHandlerRef = useRef(onMessage);
const errorHandlerRef = useRef(onError);
const kickedHandlerRef = useRef(onKicked);
// Update refs when handlers change
useEffect(() => {
customMessageHandlerRef.current = onMessage;
errorHandlerRef.current = onError;
kickedHandlerRef.current = onKicked;
}, [onMessage, onError, onKicked]);
useEffect(() => {
if (!session)
return;
const handleGameMessage = ({ data, peerId, }) => {
if (customMessageHandlerRef.current) {
customMessageHandlerRef.current(data, peerId);
}
};
const handleError = ({ code, message, context, originalError, }) => {
if (errorHandlerRef.current) {
errorHandlerRef.current(code, message, context, originalError);
}
};
const handleKicked = () => {
if (kickedHandlerRef.current) {
kickedHandlerRef.current();
}
};
// Subscribe to events
const unsubscribe1 = session.on("customMessage", handleGameMessage);
const unsubscribe2 = session.on("error", handleError);
const unsubscribe3 = session.on("kicked", handleKicked);
return () => {
unsubscribe1();
unsubscribe2();
unsubscribe3();
};
}, [session]);
}