useEventSource
Hook that provides a reactive wrapper for event source
browser
low
test coverage
Last changed: 4 months ago
TIP
This hook uses EventSource browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api
Installation
Library
CLI
Manual
typescript
import { useEventSource } from '@siberiacancode/reactuse';Usage
typescript
const { instance, data, connecting, opened, isError, close, open } = useEventSource('url', ['message']);Demo
Api
Parameters
| Name | Type | Default | Note |
|---|---|---|---|
| url | string | URL | - | The URL of the EventSource |
| events? | string[] | [] | List of events to listen to |
| options? | UseEventSourceOptions | {} | Configuration options |
Returns
UseEventSourceReturn<Data>
Type declaration
typescript
export interface UseEventSourceOptions<QueryData, Data> extends EventSourceInit {
/** Immediately open the connection when calling this hook */
immediately?: boolean;
/* The placeholder data for the hook */
placeholderData?: (() => Data) | Data;
/* The retry count of requests */
retry?: boolean | number;
/* The retry delay of requests */
retryDelay?: ((retry: number, event: Event) => number) | number;
/* The onError function to be invoked */
onError?: (error: Event) => void;
/* The onMessage function to be invoked */
onMessage?: (event: Event & { data?: Data }) => void;
/* The onOpen function to be invoked */
onOpen?: () => void;
/* The select function to be invoked */
select?: (data: QueryData) => Data;
}
interface UseEventSourceReturn<Data = any> {
/** The latest data received via the EventSource */
data?: Data;
/** The current error */
error?: Event;
/** The instance of the EventSource */
instance?: EventSource;
/* The connecting state of the query */
isConnecting: boolean;
/* The error state of the query */
isError: boolean;
/* The open state of the query */
opened: boolean;
/** Closes the EventSource connection gracefully */
close: () => void;
/** Reopen the EventSource connection */
open: () => void;
}Source
Source • DemoContributors
D
N