useEventSource
useEventSource 是一個 hook,允許您訂閱 EventSource 並實時接收更新。
即時編輯器
function Demo() { const { status, data, error, close, open } = useEventSource( "https://sse.dev/test", [], { immediate: false, } ); return ( <div> <div>狀態:{status}</div> <div>數據:{JSON.stringify(data)}</div> <div>錯誤:{error}</div> <button onClick={open}>開啟</button> <button onClick={close}>關閉</button> </div> ); }
結果
狀態:DISCONNECTED
數據:null
錯誤:
API
UseEventSourceOptions
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| immediate | 立即打开连接, 默认打开 | boolean | - |
| autoReconnect | 连接断开时自动重连 | UseEventSourceAutoReconnectOptions | - |
UseEventSourceAutoReconnectOptions
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| retries | 重试次数,如果是函数,会调用来判断是否重试 | number | (() => boolean) | - |
| delay | 重连前的延迟时间 | number | - |
| onFailed | 重连失败时的回调 | () => void | - |
UseEventSourceReturn
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| eventSourceRef | EventSource 实例 | React.MutableRefObject<EventSource | null> (必填) | - |
| data | 接收到的数据 | string | null (必填) | - |
| error | 发生的错误 | Event | null (必填) | - |
| status | 连接的状态 | EventSourceStatus (必填) | - |
| lastEventId | 最后的事件 ID | string | null (必填) | - |
| event | 事件名 | string | null (必填) | - |
| close | 关闭连接 | () => void (必填) | - |
| open | 打开连接 | () => void (必填) | - |
EventSourceStatus
export type EventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';