跳至主要内容

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

參數名描述類型預設值
eventSourceRefEventSource 实例React.MutableRefObject<EventSource | null> (必填)-
data接收到的数据string | null (必填)-
error发生的错误Event | null (必填)-
status连接的状态EventSourceStatus (必填)-
lastEventId最后的事件 IDstring | null (必填)-
event事件名string | null (必填)-
close关闭连接() => void (必填)-
open打开连接() => void (必填)-

EventSourceStatus

export type EventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';
Auth0
Your time is valuable. Use it to focus on your app, and let us handle login (and much more).
Try for Free Now