fix: socket reconnect and polling fallback

This commit is contained in:
2026-04-22 14:02:40 -04:00
parent 4b8a41d928
commit 57b09b1f99
+33 -29
View File
@@ -1,38 +1,42 @@
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from "react";
import { io, Socket } from 'socket.io-client'; import { io, type Socket } from "socket.io-client";
import { useStore } from './store'; import { useStore } from "./store";
const SOCKET_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'; const SOCKET_URL =
typeof window !== "undefined"
? window.location.origin
: process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";
export const useSocket = () => { export const useSocket = () => {
const { token, isAuthenticated } = useStore(); const { token, isAuthenticated } = useStore();
const socketRef = useRef<Socket | null>(null); const socketRef = useRef<Socket | null>(null);
useEffect(() => { useEffect(() => {
if (isAuthenticated && token) { if (isAuthenticated && token) {
// Connect to socket socketRef.current = io(SOCKET_URL, {
socketRef.current = io(SOCKET_URL, { auth: { token },
auth: { token }, transports: ["websocket", "polling"],
transports: ['websocket'], path: "/socket.io",
}); reconnection: true,
});
socketRef.current.on('connect', () => { socketRef.current.on("connect", () => {
console.log('Connected to socket'); console.log("Connected to socket");
socketRef.current?.emit('subscribe_transactions'); socketRef.current?.emit("subscribe_transactions");
}); });
socketRef.current.on('connect_error', (error) => { socketRef.current.on("connect_error", (error) => {
console.error('Socket connection error:', error); console.error("Socket connection error:", error);
}); });
return () => { return () => {
if (socketRef.current) { if (socketRef.current) {
socketRef.current.disconnect(); socketRef.current.disconnect();
socketRef.current = null; socketRef.current = null;
} }
}; };
} }
}, [isAuthenticated, token]); }, [isAuthenticated, token]);
return socketRef.current; return socketRef.current;
}; };