react-sse-consumer
v1.0.4
Published
React hook for consuming Server Sent Events (SSE). This is a wrapper built around the [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) API. Handle `EventSource` events and consume named events sent from the server.
Downloads
13
Readme
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.
- NPM: react-sse-consumer
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, ... |