Skip to content

Commit

Permalink
chore: add message queue in useWebSocket
Browse files Browse the repository at this point in the history
  • Loading branch information
vikiboss committed Sep 5, 2024
1 parent 15393d4 commit d3d81ef
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
2 changes: 1 addition & 1 deletion packages/react-use/src/use-web-socket/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { HooksType, Since } from '@/components'

<Since version="v1.7.0" />

A simplified React Hook for using WebSockets, wrapping the native WebSocket API. It supports features such as automatic reconnection and heartbeat.
A React Hook that simplifies the use of WebSockets, wrapping the native [WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) to support features like automatic reconnection, heartbeat, and message queuing.

## Scenes \{#scenes}

Expand Down
16 changes: 12 additions & 4 deletions packages/react-use/src/use-web-socket/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ export function useWebSocket(

const [wsRef, ws] = useGetterRef<WebSocket | null>(null)
const isClosedIntentionally = useRef<boolean>(false)
const messageQueue = useRef<UseWebSocketSendable[]>([])
const [incVersion, runVersionedAction] = useVersionedAction()

const [readyState, setReadyState] = useSafeState<UseWebSocketReturnsReadyState>(WebSocket.CLOSED)
Expand Down Expand Up @@ -269,7 +270,7 @@ export function useWebSocket(
{ immediate: false },
)

const heartbeatInterval = useIntervalFn(() => {
useIntervalFn(() => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN && latest.current.heartbeat) {
const message =
latest.current.heartbeat === true
Expand All @@ -289,9 +290,7 @@ export function useWebSocket(
if (wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.send(data)
} else {
if (isDev) {
console.error('WebSocket is not open, unable to send data:', data)
}
messageQueue.current.push(data)
}
}
})
Expand Down Expand Up @@ -324,6 +323,15 @@ export function useWebSocket(
openWithRetry()
}, [_url])

useUpdateEffect(() => {
if (readyState === WebSocket.OPEN) {
if (messageQueue.current.length) {
for (const message of messageQueue.current) send(message)
messageQueue.current = []
}
}
}, [readyState])

return {
ws,
readyState,
Expand Down
2 changes: 1 addition & 1 deletion packages/react-use/src/use-web-socket/index.zh-cn.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { HooksType, Since } from '@/components'

<Since version="v1.7.0" />

一个简化 WebSocket 使用的 React Hook,是原生 WebSocket API 的包装,支持自动重连、心跳包等
一个简化 WebSocket 使用的 React Hook,是原生 [WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) 的包装,支持自动重连、心跳包、消息队列等功能

## 场景 \{#scenes}

Expand Down

0 comments on commit d3d81ef

Please sign in to comment.