1.3.2 • Published 2 years ago
@sse-lib/react-sse v1.3.2
react-sse
react-sse
is a library for interacting with
Server-Sent Events
from your react application.
Learn more about SSE on MDN
Installation
Use npm
npm i @sse-lib/react-sse
or yarn
yarn add @sse-lib/react-sse
Pre-requirements
Each event received from the back-end must contain field called serverEventType
in final json.
It's necessary for correct work of library
For example:
{
"serverEventType": "newUser",
... other users defined fields
}
Usage
Wrap your application in a provider
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
import { EventsProvider } from "@sse-lib/react-sse"
ReactDOM.render(
<EventsProvider url="https://example.com/sse">
<App />
</EventsProvider>,
document.getElementById("root")
)
Parameters:
value | description |
---|---|
url | url to your sse end-point |
withCredentials | enable CORS (default false ) |
Hook
Inside your component supposed to use useEventSource
hook.
import { useEffect } from 'react'
import { useEventSource } from "@sse-lib/react-sse"
function App() {
const { data, unsubscribe } = useEventSource("event-name")
useEffect(() => {
return () => {
unsubscribe()
}
}, [])
return (
...
)
}
Hook subscribe to the event immediately after the component is mounted and will unsubscribe after unmounting automatically.
Returned values:
| value | description |
| --- | --- |
| data
| the value from the MessageEvent of the EventSource instance |
| unsubscribe
| callback function which triggers hook to unsubscribe from event manually |