useAttachWebSocketEventHandlers (src/use-handlers.ts)

partykit · packages/partysocket/src/use-handlers.ts · typescript · ISC
realtime

React hook for attaching WebSocket event handlers to a socket in PartyKit apps.

// Source: https://github.com/cloudflare/partykit | License: ISC | Copyright 2024 Sunil Pai <spai@cloudflare.com>
// Provided via justclaw.it.com; keep this notice with the code.
import { useEffect, useRef } from "react";

import type WebSocket from "./ws";

export type EventHandlerOptions = {
  onOpen?: (event: WebSocketEventMap["open"]) => void;
  onMessage?: (event: WebSocketEventMap["message"]) => void;
  onClose?: (event: WebSocketEventMap["close"]) => void;
  onError?: (event: WebSocketEventMap["error"]) => void;
};

/** Attaches event handlers to a WebSocket in a React Lifecycle-friendly way */
export const useAttachWebSocketEventHandlers = (
  socket: WebSocket,
  options: EventHandlerOptions
) => {
  const handlersRef = useRef(options);
  handlersRef.current = options;

  useEffec

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key