Something went wrong. Try again.
Starship Simulator Controls thoriumsim.com
Something went wrong. Try again.
1.2 kB · 35 lines
TypeScript
at develop
123456789101112131415161718192021222324252627282930313233343536import uniqid from "@thorium/utils/uniqid";import { useEffect, useState } from "react";
import { useLiveQuery } from "./liveQueryContext";import { stableValueHash } from "./stableValueHash";
const requestMap = new Map<string, Set<string>>();
export function useRequestSub(requestParams: { path: string; params?: any }, mockData?: any) { const id = stableValueHash([requestParams.path, requestParams.params]); const [hookId] = useState(uniqid()); const { socket, reconnectionState } = useLiveQuery(); const isConnected = reconnectionState === "connected"; useEffect(() => { if (!socket || !isConnected || mockData) return; if (!requestMap.has(id)) { requestMap.set(id, new Set()); } if (requestMap.get(id)?.size === 0) { // Subscribe to the effect socket.send("netRequest", { ...requestParams, id: id }); }
requestMap.get(id)?.add(hookId);
return () => { requestMap.get(id)?.delete(hookId); if (!requestMap.get(id) || requestMap.get(id)?.size === 0) { // Unsubscribe from the effect socket.send("netRequestEnd", { id: id }); } }; // The request ID is a stable way to represent the missing dependencies }, [socket, hookId, id, isConnected]);}