Skip to content

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.

License

Notifications You must be signed in to change notification settings

heshanera/react-sse-consumer

Repository files navigation

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, ...

About

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.

Resources

License

Stars

Watchers

Forks

Packages

No packages published