useFetchEventSource
useFetchEventSource
is a hook that allows you to subscribe to an EventSource using HTTP methods like POST and receive updates in real-time.
note
This example don't work in the live editor because it requires a server to send events. You can try it in your local environment.
Example Server Code:
SSE Server Implementation
Examples
Basic Usage
Live Editor
function Demo() { const { data, status } = useFetchEventSource("https://broad-scene-1112.ploomberapp.io/stream", { openWhenHidden: false }); return ( <div> <div>Status: {status}</div> <div>Data: {JSON.stringify(data)}</div> </div> ); };
Result
Status: DISCONNECTED
Data: null
With POST Request
Live Editor
function Demo() { const { status, data, error, close, open } = useFetchEventSource( "http://localhost:3001/events", { method: "POST", headers: { "Content-Type": "application/json", Accept: "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }, immediate: false, // Don't connect immediately body: JSON.stringify({ channel: "custom-channel", interval: 2000 }), } ); return ( <div> <div>Status: {status}</div> <div>Data: {JSON.stringify(data)}</div> <div>Error: {error?.message}</div> <button onClick={open}>Open</button> <button onClick={close}>Close</button> </div> ); };
Result
Status: DISCONNECTED
Data: null
Error:
With Event Handlers
Live Editor
function Demo() { const { data, status } = useFetchEventSource("http://localhost:3001/events", { onOpen: () => { console.log("Connection established"); }, onMessage: (event) => { console.log("New message:", event.data); }, onError: (error) => { console.error("Connection error:", error); return 5000; // Retry after 5 seconds }, onClose: () => { console.log("Connection closed"); } }); return ( <div> <div>Status: {status}</div> <div>Latest message: {JSON.stringify(data)}</div> </div> ); };
Result
Status: DISCONNECTED
Latest message: null
With Auto Reconnect
Live Editor
function Demo() { const { status, data } = useFetchEventSource("http://localhost:3001/events", { autoReconnect: { retries: 3, // Maximum retry attempts delay: 1000, // Delay between retries (ms) onFailed: () => { console.log("Failed to reconnect after 3 attempts"); } } }); return ( <div> <div>Connection status: {status}</div> <div>Data: {JSON.stringify(data)}</div> </div> ); };
Result
Connection status: DISCONNECTED
Data: null
Multi Channel Example
Live Editor
function Demo() { const [channel, setChannel] = useState('default'); const { data, close, open } = useFetchEventSource( "http://localhost:3001/events", { method: "POST", immediate: false, body: JSON.stringify({ channel }), onMessage: (event) => { console.log(`Message from ${channel}:`, event); } } ); const switchChannel = (newChannel) => { close(); setChannel(newChannel); open(); }; return ( <div> <select value={channel} onChange={(e) => switchChannel(e.target.value)} > <option value="default">Default Channel</option> <option value="news">News Channel</option> <option value="alerts">Alerts Channel</option> </select> <div>Current Channel: {channel}</div> <div>Latest Message: {data?.message}</div> </div> ); };
Result
Current Channel: default
Latest Message:
API
UseFetchEventSourceStatus
Type
export type UseFetchEventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED'
UseFetchEventSourceAutoReconnectOptions
Property | Description | Type | DefaultValue |
---|---|---|---|
retries | The number of retries, if it is a function, it will be called to determine whether to retry | number | (() => boolean) | - |
delay | The delay time before reconnecting (ms) | number | - |
onFailed | Callback when reconnection fails | () => void | - |
UseFetchEventSourceOptions
Property | Description | Type | DefaultValue |
---|---|---|---|
method | HTTP method for the request | string | - |
headers | Request headers | Record<string, string> | - |
body | Request body for POST requests | any | - |
withCredentials | Use credentials | boolean | - |
immediate | Immediately open the connection, enabled by default | boolean | - |
autoReconnect | Automatically reconnect when the connection is disconnected | UseFetchEventSourceAutoReconnectOptions | - |
onOpen | Callback when connection opens | () => void | - |
onMessage | Callback when message received | (event: UseFetchEventSourceMessage) => void | - |
onError | Callback when error occurs, return number to retry after specified milliseconds | (error: Error) => number | void | null | undefined | - |
onClose | Callback when connection closes | () => void | - |
UseFetchEventSourceMessage
Property | Description | Type | DefaultValue |
---|---|---|---|
id | The event ID | string | null (Required) | - |
event | The event type | string | null (Required) | - |
data | The event data | string (Required) | - |
UseFetchEventSourceReturn
Property | Description | Type | DefaultValue |
---|---|---|---|
data | The data received | string | null (Required) | - |
error | The error occurred | Error | null (Required) | - |
status | The status of the connection | UseFetchEventSourceStatus (Required) | - |
lastEventId | The last event ID | string | null (Required) | - |
event | The event name | string | null (Required) | - |
close | Close the connection | () => void (Required) | - |
open | Open the connection | () => void (Required) | - |
UseFetchEventSource
Returns
UseFetchEventSourceReturn
Arguments
Argument | Description | Type | DefaultValue |
---|---|---|---|
url | The URL of the server-sent event | string | URL (Required) | - |
options | EventSource options | UseFetchEventSourceOptions | undefined | - |