Appearance
useEventSource
An EventSource or Server-Sent-Events instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format.
Demo
Usage
tsx
import { useEventSource } from '@reause/core'
const { status, data, error, close } = useEventSource('https://event-source-url')Named Events
You can define named events with the second parameter:
tsx
import { useEventSource } from '@reause/core'
const { event, data } = useEventSource(
'https://event-source-url',
['notice', 'update'],
)immediate
Enable by default.
Establish the connection immediately when the hook is called.
autoConnect
Enable by default.
If the URL is provided as a React ref object, when the URL changes the hook will automatically reconnect to the new URL.
Auto Reconnection on Errors
Reconnect on errors automatically (disabled by default).
tsx
import { useEventSource } from '@reause/core'
const { status, data, close } = useEventSource(
'https://event-source-url',
[],
{
autoReconnect: true,
},
)Or with more controls over its behavior:
tsx
import { useEventSource } from '@reause/core'
const { status, data, close } = useEventSource(
'https://event-source-url',
[],
{
autoReconnect: {
retries: 3,
delay: 1000,
onFailed() {
alert('Failed to connect EventSource after 3 retries')
},
},
},
)Data Serialization
Apply custom transformations to incoming data using a serialization function.
tsx
import { useEventSource } from '@reause/core'
const { data } = useEventSource(
'https://event-source-url',
[],
{
serializer: {
read: rawData => JSON.parse(rawData),
},
},
)
// If server sends: '{"name":"John","age":30}'
// data will be: { name: 'John', age: 30 }Type Declarations
ts
export type EventSourceStatus = 'CONNECTING' | 'OPEN' | 'CLOSED'
export interface UseEventSourceOptions<Data> extends EventSourceInit {
autoReconnect?: boolean | {
retries?: number | (() => boolean);
delay?: number;
onFailed?: () => void;
};
immediate?: boolean;
autoConnect?: boolean;
serializer?: {
read: (v?: string) => Data;
};
}
export interface UseEventSourceReturn<Events extends string[], Data = any> {
data: Data | null;
status: EventSourceStatus;
event: Events[number] | null;
error: Event | null;
close: () => void;
open: () => void;
eventSource: EventSource | null;
lastEventId: string | null;
}
export function useEventSource<Events extends string[], Data = any>(url: string | URL | undefined, events?: Events, options?: UseEventSourceOptions<Data>): UseEventSourceReturn<Events, Data>