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
npm i react-sse-consumer
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);
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);
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,
);
Prop | Type | Description |
---|---|---|
EventHandlers | object |
Handlers for the EventSource events onerror , onopen , onmessage |
EventListeners | object |
Listeners for consuming named events message , ... |