feat: auto reconnect hosts when app resumes

This commit is contained in:
Mohamed Boudra
2025-11-26 19:26:27 +01:00
parent 881f0e7a8b
commit 393aa44e68
2 changed files with 34 additions and 11 deletions

View File

@@ -1,4 +1,5 @@
import { useEffect, useRef, useState, useCallback, useMemo } from "react";
import { AppState } from "react-native";
import type {
WSInboundMessage,
WSOutboundMessage,
@@ -176,6 +177,27 @@ export function useWebSocket(url: string, conversationId?: string | null): UseWe
};
}, [connect]);
useEffect(() => {
const subscription = AppState.addEventListener("change", (nextState) => {
if (nextState !== "active") {
return;
}
const readyState = wsRef.current?.readyState;
if (readyState === WebSocket.OPEN || readyState === WebSocket.CONNECTING) {
return;
}
shouldReconnectRef.current = true;
setIsConnecting(true);
connect();
});
return () => {
subscription.remove();
};
}, [connect]);
const send = useCallback((message: WSInboundMessage) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(message));