1.3.2 • Published 2 years ago

@sse-lib/react-sse v1.3.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

react-sse

npm version

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:

valuedescription
urlurl to your sse end-point
withCredentialsenable 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 |

License

MIT

1.3.2

2 years ago

1.3.1

3 years ago

1.2.0

3 years ago

1.3.0

3 years ago

1.1.0

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago