useFetchEventSource
useFetchEventSource 是一個 React Hook,允許你使用 POST 等 HTTP 方法訂閱 EventSource 並實時接收更新。
備註
這個例子在實時編輯器中不起作用,因為它需要一個服務器來發送事件。你可以在本地環境中嘗試它。
服务端代码示范:
SSE Server Implementation
示例
基础用法
即時編輯器
function Demo() { const { data, status } = useFetchEventSource("https://broad-scene-1112.ploomberapp.io/stream", { openWhenHidden: false }); return ( <div> <div>狀態: {status}</div> <div>数据: {JSON.stringify(data)}</div> </div> ); }
結果
狀態: DISCONNECTED
数据: null
POST 请求示例
即時編輯器
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, // 不立即連接 body: JSON.stringify({ channel: "custom-channel", // 訂閱特定频道 interval: 2000 // 消息间隔(毫秒) }), } ); return ( <div> <div>狀態: {status}</div> <div>数据: {JSON.stringify(data)}</div> <div>错误: {error?.message}</div> <button onClick={open}>开启</button> <button onClick={close}>关闭</button> </div> ); }
結果
狀態: DISCONNECTED
数据: null
错误:
事件處理示例
即時編輯器
function Demo() { const { data, status } = useFetchEventSource("http://localhost:3001/events", { onOpen: () => { console.log("連接已建立"); }, onMessage: (event) => { console.log("收到新消息:", event.data); }, onError: (error) => { console.error("連接错误:", error); return 5000; // 5秒后重试 }, onClose: () => { console.log("連接已关闭"); } }); return ( <div> <div>連接狀態: {status}</div> <div>最新消息: {JSON.stringify(data)}</div> </div> ); }
結果
連接狀態: DISCONNECTED
最新消息: null
自动重连示例
即時編輯器
function Demo() { const { status, data } = useFetchEventSource("http://localhost:3001/events", { autoReconnect: { retries: 3, // 最大重试次数 delay: 1000, // 重试间隔(毫秒) onFailed: () => { console.log("三次重试后連接失败"); } } }); return ( <div> <div>連接狀態: {status}</div> <div>数据: {JSON.stringify(data)}</div> </div> ); }
結果
連接狀態: DISCONNECTED
数据: null
多频道示例
即時編輯器
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(`收到来自 ${channel} 的消息:`, event); } } ); const switchChannel = (newChannel) => { close(); // 关闭当前連接 setChannel(newChannel); open(); // 开启新連接 }; return ( <div> <select value={channel} onChange={(e) => switchChannel(e.target.value)} > <option value="default">默认频道</option> <option value="news">新闻频道</option> <option value="alerts">提醒频道</option> </select> <div>当前频道: {channel}</div> <div>最新消息: {data?.message}</div> </div> ); }
結果
当前频道: default
最新消息:
API
UseFetchEventSourceStatus
Type
export type UseFetchEventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED'
UseFetchEventSourceAutoReconnectOptions
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| retries | 重试次数,如果是函数,会调用来判断是否重试 | number | (() => boolean) | - |
| delay | 重连前的延迟时间(毫秒) | number | - |
| onFailed | 重连失败时的回调 | () => void | - |
UseFetchEventSourceOptions
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| method | HTTP 请求方法 | string | - |
| headers | 请求头 | Record<string, string> | - |
| body | POST 请求的请求体 | any | - |
| withCredentials | 使用凭证 | boolean | - |
| immediate | 立即打开连接,默认打开 | boolean | - |
| autoReconnect | 连接断开时自动重连 | UseFetchEventSourceAutoReconnectOptions | - |
| onOpen | 连接打开时的回调 | () => void | - |
| onMessage | 接收到消息时的回调 | (event: UseFetchEventSourceMessage) => void | - |
| onError | 发生错误时的回调,返回数字表示多少毫秒后重试 | (error: Error) => number | void | null | undefined | - |
| onClose | 连接关闭时的回调 | () => void | - |
UseFetchEventSourceMessage
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| id | 事件 ID | string | null (必填) | - |
| event | 事件类型 | string | null (必填) | - |
| data | 事件数据 | string (必填) | - |
UseFetchEventSourceReturn
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| data | 接收到的数据 | string | null (必填) | - |
| error | 发生的错误 | Error | null (必填) | - |
| status | 连接的状态 | UseFetchEventSourceStatus (必填) | - |
| lastEventId | 最后的事件 ID | string | null (必填) | - |
| event | 事件名 | string | null (必填) | - |
| close | 关闭连接 | () => void (必填) | - |
| open | 打开连接 | () => void (必填) | - |
UseFetchEventSource
Returns
UseFetchEventSourceReturn
Arguments
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| url | 服务器发送事件的 URL | string | URL (必填) | - |
| options | EventSource 选项 | UseFetchEventSourceOptions | undefined | - |