Skip to content

Latest commit

 

History

History
83 lines (67 loc) · 3.39 KB

README.md

File metadata and controls

83 lines (67 loc) · 3.39 KB

react-sse-consumer

React hook for consuming Server Sent Events (SSE). This is a wrapper built around the EventSource API. Handle EventSource events and consume named events sent from the server.

React   NPM  Node  License: MIT 

Usage

npm i react-sse-consumer

Consuming events

import useSseConsumer from 'react-sse-consumer';

const resourceUrl = 'path/to/resource';
const options = {};
const eventHandlers = {
  onerror: (event) => { /* handle error */ },
  onopen: (event) => { /* handle connection open */ },
  onmessage: (messageEvent) => { /* handle consumed events */ },
};

const eventConsumer = useSseConsumer(resourceUrl, options, eventHandlers);

Consuming named events

import useSseConsumer from 'react-sse-consumer';

const resourceUrl = 'path/to/resource';
const options = {};
const eventHandlers = {
  onerror: (event) => { /* handle error */ },
  onopen: (event) => { /* handle connection open */ },
  onmessage: (messageEvent) => { /* handle consumed events */ },
};
const eventListeners = {
  message: (messageEvent) => { /* handle named event 'message' */ },
  ping: (messageEvent) => { /* handle named event 'ping' */ },
  ...
};

const eventConsumer = useSseConsumer(resourceUrl, options, eventHandlers, eventListeners);

Typescript

import useSseConsumer, { EventHandlers, EventListeners } from 'react-sse-consumer';

const resourceUrl = 'path/to/resource';
const options: object = {};
const eventHandlers: EventHandlers = {
  onerror: (event: Event) => { /* handle error */ },
  onopen: (event: Event) => { /* handle connection open */ },
  onmessage: (messageEvent: MessageEvent) => { /* handle consumed events */ },
};
const eventListeners: EventListeners = {
  message: (messageEvent: MessageEvent) => { /* handle named event 'message' */ },
  ping: (messageEvent: MessageEvent) => { /* handle named event 'ping' */ },
};

const eventConsumer: EventSource | null = useSseConsumer(
  resourceUrl,
  options,
  eventHandlers,
  eventListeners,
);

Consumer Props

Prop Type Description
EventHandlers object Handlers for the EventSource events
onerror, onopen, onmessage
EventListeners object Listeners for consuming named events
message, ...