joel-woodfield's picture
Refactor file structure
7b67454
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<WebSocketApi>(new WebSocketApi());
const [plotData, setPlotData] = useState<PlotData>({});
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),
};
}