mirror of
https://github.com/streamyfin/streamyfin.git
synced 2026-01-15 15:48:05 +00:00
fix(websocket): persist reconnect counter across retry attempts
Move reconnectAttempts from local variable to useRef so it persists across recursive connectWebSocket calls. Previously, each call reset the counter to 0, causing infinite reconnection attempts instead of stopping at the max of 5. Also reset the counter on successful connection (onopen) so fresh reconnection attempts get full retries.
This commit is contained in:
@@ -8,6 +8,7 @@ import {
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { AppState, type AppStateStatus } from "react-native";
|
||||
@@ -42,6 +43,7 @@ export const WebSocketProvider = ({ children }: WebSocketProviderProps) => {
|
||||
const deviceId = useMemo(() => {
|
||||
return getOrSetDeviceId();
|
||||
}, []);
|
||||
const reconnectAttemptsRef = useRef(0);
|
||||
|
||||
const connectWebSocket = useCallback(() => {
|
||||
if (!deviceId || !api?.accessToken) {
|
||||
@@ -58,9 +60,13 @@ export const WebSocketProvider = ({ children }: WebSocketProviderProps) => {
|
||||
const newWebSocket = new WebSocket(url);
|
||||
let keepAliveInterval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const maxReconnectAttempts = 5;
|
||||
const reconnectDelay = 10000;
|
||||
|
||||
newWebSocket.onopen = () => {
|
||||
console.log("WebSocket connection opened");
|
||||
setIsConnected(true);
|
||||
reconnectAttemptsRef.current = 0;
|
||||
keepAliveInterval = setInterval(() => {
|
||||
if (newWebSocket.readyState === WebSocket.OPEN) {
|
||||
newWebSocket.send(JSON.stringify({ MessageType: "KeepAlive" }));
|
||||
@@ -68,18 +74,16 @@ export const WebSocketProvider = ({ children }: WebSocketProviderProps) => {
|
||||
}, 30000);
|
||||
};
|
||||
|
||||
let reconnectAttempts = 0;
|
||||
const maxReconnectAttempts = 5;
|
||||
const reconnectDelay = 10000;
|
||||
|
||||
newWebSocket.onerror = (e) => {
|
||||
console.error("WebSocket error:", e);
|
||||
setIsConnected(false);
|
||||
|
||||
if (reconnectAttempts < maxReconnectAttempts) {
|
||||
reconnectAttempts++;
|
||||
if (reconnectAttemptsRef.current < maxReconnectAttempts) {
|
||||
reconnectAttemptsRef.current++;
|
||||
setTimeout(() => {
|
||||
console.log(`WebSocket reconnect attempt ${reconnectAttempts}`);
|
||||
console.log(
|
||||
`WebSocket reconnect attempt ${reconnectAttemptsRef.current}`,
|
||||
);
|
||||
connectWebSocket();
|
||||
}, reconnectDelay);
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user