import { useEffect, useRef, useState } from "react"; import { DataNet } from "@sjs/sdk"; const CHANNEL = "demo.json.state"; export function StateSyncDemo({ apiKey }: { apiKey: string }) { const clientRef = useRef(null); const [mode, setMode] = useState("idle"); const [enabled, setEnabled] = useState(true); const [position, setPosition] = useState({ x: 120, y: 84 }); useEffect(() => { const client = new DataNet({ apiKey, clientId: "react-state-demo", deviceName: "React State Demo", }); clientRef.current = client; client.on("connect", () => console.log("react connected")); client.on("error", (err) => console.error(err)); client.subscribe(CHANNEL, (data) => { const next = data as { mode?: string; enabled?: boolean; position?: { x?: number; y?: number } }; if (next.mode) setMode(next.mode); if (typeof next.enabled === "boolean") setEnabled(next.enabled); if (next.position?.x != null && next.position?.y != null) { setPosition({ x: next.position.x, y: next.position.y }); } }); void client.connect(); return () => client.disconnect(); }, [apiKey]); function publishState(nextMode: string) { const payload = { mode: nextMode, enabled, position, source: "react-demo", }; clientRef.current?.publish(CHANNEL, payload); setMode(nextMode); } return (

React state sync

Channel: {CHANNEL}

Mode: {mode}

Enabled: {enabled ? "true" : "false"}

Position: {position.x}, {position.y}

); }