Skip to content

useEventSource ​

Hook that provides a reactive wrapper for event source

browser
test coverage
Last changed: last month

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, isConnecting, isOpen, isError, close, open } = useEventSource('url', ['message']);

Demo ​

Api ​

Parameters

NameTypeDefaultNote
urlstring | 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 */
  isOpen: boolean;
  /** Closes the EventSource connection gracefully */
  close: () => void;
  /** Reopen the EventSource connection */
  open: () => void;
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin
N
nailgilmanov
nailgilmanov

Released under the MIT License.