useEventSource
See: EventSource or Server-Sent-Events connection to an HTTP server, which sends events in text/event-stream format.
Types
UseEventSourceProps
@templateT Expected type of the parsed message data.
Configuration object accepted by useEventSource.
| Property | Type | Required | Description |
|---|---|---|---|
url | string \| URL | URL of the SSE endpoint. Can be set here or passed to open() at connection time. If omitted, open() must always be called with a URL. | |
opts | EventSourceInit | Options forwarded to the EventSource constructor. The most useful option is { withCredentials: true } for cross-origin SSE endpoints that require cookies or HTTP auth. | |
events | { name: string; handler?: (evt: MessageEvent) => void }[] | Array of named events to listen to on the EventSource. Each entry registers a listener for the named event type alongside the default "message" listener. | |
immediateConnection | boolean | When true, the EventSource connection is opened immediately on mount. When false (default), call open() to connect. | |
onOpen | (evt: Event) => void | Called when the EventSource connection is established (open event). | |
onError | (evt: Event) => void | Called when an error occurs on the EventSource connection (error event). This includes connection errors and server-side errors. | |
onMessage | <T>(evt: MessageEvent<T>) => void | Called for every unnamed "message" event received from the server. |
UseEventSourceResult
@templateT Expected type of the parsed message data.
Result object returned by useEventSource.
| Property | Type | Required | Description |
|---|---|---|---|
status | "READY" \| "CONNECTING" \| "OPENED" \| "CLOSED" | ✓ | Current connection state of the EventSource: - "READY" — not yet connected (initial state). - "CONNECTING" — connection attempt in progress. - "OPENED" — connection established, receiving events. - "CLOSED" — connection closed (manually or by the server). |
data | T \| null | ✓ | The most recently received "message" event data. null before the first message arrives. |
open | (url?: string) => void | ✓ | Opens the EventSource connection to the provided (or configured) URL. |
close | () => void | ✓ | Closes the EventSource connection. The status transitions to "CLOSED". |
