Usage Guide

Implementing this hook is straightforward. All you need is to parse the URL parameters and render a QR code.

Unified Implementation

You can handle both Host and Client logic in a single component. If the warp_id parameter exists in the URL, the hook automatically becomes a receiver.

App.tsx
tsx
import { useEffect, useState } from "react";
import QRCode from "react-qr-code";
import { useStateWarp } from "react-state-warp";

function App() {
  const [sessionId, setSessionId] = useState<string | undefined>();

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const id = params.get("warp_id");
    if (id) setSessionId(id);
  }, []);

  const { data, send, connectionLink, isConnected, peerId, isHost } =
    useStateWarp(
      { text: "", count: 0 },
      { initialSessionId: sessionId }
    );

  return (
    <div>
      <h3>Mode: {isHost ? "💻 Host" : "📱 Client"}</h3>
      <p>Status: {isConnected ? "🟢 Connected" : "🔴 Waiting"}</p>

      <textarea
        value={data.text}
        onChange={(e) => send({ ...data, text: e.target.value })}
      />
      <button onClick={() => send({ ...data, count: data.count + 1 })}>
        Count is: {data.count}
      </button>

      {isHost && connectionLink && !isConnected && (
        <div>
          <p>Scan to teleport state:</p>
          <QRCode value={connectionLink} />
        </div>
      )}
    </div>
  );
}

export default App;