fix: socket reconnect and polling fallback
This commit is contained in:
+33
-29
@@ -1,38 +1,42 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
import { useStore } from './store';
|
||||
import { useEffect, useRef } from "react";
|
||||
import { io, type Socket } from "socket.io-client";
|
||||
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 = () => {
|
||||
const { token, isAuthenticated } = useStore();
|
||||
const socketRef = useRef<Socket | null>(null);
|
||||
const { token, isAuthenticated } = useStore();
|
||||
const socketRef = useRef<Socket | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated && token) {
|
||||
// Connect to socket
|
||||
socketRef.current = io(SOCKET_URL, {
|
||||
auth: { token },
|
||||
transports: ['websocket'],
|
||||
});
|
||||
useEffect(() => {
|
||||
if (isAuthenticated && token) {
|
||||
socketRef.current = io(SOCKET_URL, {
|
||||
auth: { token },
|
||||
transports: ["websocket", "polling"],
|
||||
path: "/socket.io",
|
||||
reconnection: true,
|
||||
});
|
||||
|
||||
socketRef.current.on('connect', () => {
|
||||
console.log('Connected to socket');
|
||||
socketRef.current?.emit('subscribe_transactions');
|
||||
});
|
||||
socketRef.current.on("connect", () => {
|
||||
console.log("Connected to socket");
|
||||
socketRef.current?.emit("subscribe_transactions");
|
||||
});
|
||||
|
||||
socketRef.current.on('connect_error', (error) => {
|
||||
console.error('Socket connection error:', error);
|
||||
});
|
||||
socketRef.current.on("connect_error", (error) => {
|
||||
console.error("Socket connection error:", error);
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (socketRef.current) {
|
||||
socketRef.current.disconnect();
|
||||
socketRef.current = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [isAuthenticated, token]);
|
||||
return () => {
|
||||
if (socketRef.current) {
|
||||
socketRef.current.disconnect();
|
||||
socketRef.current = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [isAuthenticated, token]);
|
||||
|
||||
return socketRef.current;
|
||||
return socketRef.current;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user