Skip to content

useEventSource

Category
Export Size
802 B
Last Changed
5 days ago

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>

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
45eac - fix(core): resolve useEventSource audit findings (#554)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8