Skip to content

Commit

Permalink
fix: 修复readyState判断问题
Browse files Browse the repository at this point in the history
  • Loading branch information
dongmucat committed Dec 10, 2024
1 parent c7bb04c commit 73d9ff7
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions packages/hooks/src/useWebSocket/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,19 @@ export default function useWebSocket(socketUrl: string, options: Options = {}):
protocols,
} = options;

const [latestMessage, setLatestMessage] = useState<WebSocketEventMap['message']>();
const [readyState, setReadyState] = useState<ReadyState>(ReadyState.Closed);

const onOpenRef = useLatest(onOpen);
const onCloseRef = useLatest(onClose);
const onMessageRef = useLatest(onMessage);
const onErrorRef = useLatest(onError);
const readyStateRef = useLatest(readyState);

const reconnectTimesRef = useRef(0);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout>>();
const websocketRef = useRef<WebSocket>();

const [latestMessage, setLatestMessage] = useState<WebSocketEventMap['message']>();
const [readyState, setReadyState] = useState<ReadyState>(ReadyState.Closed);

const reconnect = () => {
if (
reconnectTimesRef.current < reconnectLimit &&
Expand Down Expand Up @@ -123,7 +124,7 @@ export default function useWebSocket(socketUrl: string, options: Options = {}):
};

const sendMessage: WebSocket['send'] = (message) => {
if (readyState === ReadyState.Open) {
if (readyStateRef.current === ReadyState.Open) {
websocketRef.current?.send(message);
} else {
throw new Error('WebSocket disconnected');
Expand Down

0 comments on commit 73d9ff7

Please sign in to comment.