Skip to content
On this page

useEventSource

Category
Export Size
1.21 kB
Last Changed
7 months ago

An EventSource or Server-Sent-Events instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format.

Usage

js
import { useEventSource } from '@vueuse/core'

const { status, data, error, close } = useEventSource('https://event-source-url')
import { useEventSource } from '@vueuse/core'

const { status, data, error, close } = useEventSource('https://event-source-url')
StateTypeDescription
statusRef<string>A read-only value representing the state of the connection. Possible values are CONNECTING (0), OPEN (1), or CLOSED (2)
dataRef<string | null>Reference to the latest data received via the EventSource, can be watched to respond to incoming messages
eventSourceRef<EventSource | null>Reference to the current EventSource instance
MethodSignatureDescription
close() => voidCloses the EventSource connection gracefully.

Type Declarations

typescript
export type UseEventSourceOptions = EventSourceInit
/**
 * Reactive wrapper for EventSource.
 *
 * @see https://vueuse.org/useEventSource
 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource EventSource
 * @param url
 * @param events
 * @param options
 */
export declare function useEventSource(
  url: string,
  events?: Array<string>,
  options?: UseEventSourceOptions
): {
  eventSource: Ref<EventSource | null>
  event: Ref<string | null>
  data: Ref<string | null>
  status: Ref<"OPEN" | "CONNECTING" | "CLOSED">
  error: Ref<Event | null>
  close: () => void
}
export type UseEventSourceReturn = ReturnType<typeof useEventSource>
export type UseEventSourceOptions = EventSourceInit
/**
 * Reactive wrapper for EventSource.
 *
 * @see https://vueuse.org/useEventSource
 * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource EventSource
 * @param url
 * @param events
 * @param options
 */
export declare function useEventSource(
  url: string,
  events?: Array<string>,
  options?: UseEventSourceOptions
): {
  eventSource: Ref<EventSource | null>
  event: Ref<string | null>
  data: Ref<string | null>
  status: Ref<"OPEN" | "CONNECTING" | "CLOSED">
  error: Ref<Event | null>
  close: () => void
}
export type UseEventSourceReturn = ReturnType<typeof useEventSource>

Source

SourceDocs

Contributors

Anthony Fu
Antério Vieira
Jelf
Shinigami
江麻妞
Shinigami
Alex Kozack
Johnson Chen
Charles

Changelog

v8.9.3 on 7/14/2022
a5192 - fix!: return type should be UseEventSourceReturn (#1864)

Released under the MIT License.