import { useState, useRef, useEffect } from "react"; import WebSocketApi from "./websocket.ts"; import type { PlotData, Settings } from "./types.ts"; export default function useApi(url: string) { const api = useRef(new WebSocketApi()); const [plotData, setPlotData] = useState({}); api.current.onMessage( (data: unknown) => { // todo data validation / type setPlotData((prevData) => ({ ...prevData, ...(data as PlotData) })); } ) useEffect(() => { api.current.connect(url); return () => api.current.disconnect(); }, [url]); return { plotData, sendInit: (settings: Settings) => api.current.sendInit(settings), sendReset: () => api.current.sendReset(), sendNextStep: () => api.current.sendNextStep(), sendPrevStep: () => api.current.sendPrevStep(), sendPlay: () => api.current.sendPlay(), sendPause: () => api.current.sendPause(), onReconnect: (handler: () => void) => api.current.onReconnect(handler), }; }