Spaces:
Paused
Paused
File size: 975 Bytes
48f3216 c8cd24f 48f3216 c8cd24f 48f3216 c8cd24f 48f3216 c8cd24f 48f3216 c8cd24f 48f3216 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import { useEffect } from "react";
import { useBattleStore } from "../stores/battleStore";
export function useBattleWebSocket(sessionId?: string) {
const pushEvent = useBattleStore((s) => s.pushEvent);
const setStatus = useBattleStore((s) => s.setStatus);
const setError = useBattleStore((s) => s.setError);
useEffect(() => {
if (!sessionId) return;
const proto = window.location.protocol === "https:" ? "wss" : "ws";
const ws = new WebSocket(`${proto}://${window.location.host}/ws/battle/${sessionId}`);
setStatus("running");
ws.onmessage = (evt) => {
try {
const payload = JSON.parse(evt.data);
if (payload?.event === "ping") return;
pushEvent(payload);
} catch {
// Ignore malformed packets.
}
};
ws.onerror = () => setError("WebSocket disconnected.");
ws.onclose = () => setStatus("stopped");
return () => ws.close();
}, [sessionId, pushEvent, setError, setStatus]);
}
|