MAJOR FIX: Chat Latency Fixed
This commit is contained in:
57
frontend/src/context/SocketContext.tsx
Normal file
57
frontend/src/context/SocketContext.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
|
||||
interface SocketContextType {
|
||||
socket: Socket | null;
|
||||
isConnected: boolean;
|
||||
}
|
||||
|
||||
const SocketContext = createContext<SocketContextType | undefined>(undefined);
|
||||
|
||||
export const SocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [socket, setSocket] = useState<Socket | null>(null);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const newSocket = io("http://localhost:8080", {
|
||||
path: "/socket.io/",
|
||||
withCredentials: true,
|
||||
transports: ['websocket'],
|
||||
upgrade: false
|
||||
});
|
||||
|
||||
newSocket.on('connect', () => {
|
||||
console.log('Socket connected!');
|
||||
setIsConnected(true);
|
||||
});
|
||||
|
||||
newSocket.on('connect_error', (error) => {
|
||||
console.error('Socket connection error:', error);
|
||||
});
|
||||
|
||||
newSocket.on('disconnect', () => {
|
||||
console.log('Socket disconnected!');
|
||||
setIsConnected(false);
|
||||
});
|
||||
|
||||
setSocket(newSocket);
|
||||
|
||||
return () => {
|
||||
newSocket.close();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SocketContext.Provider value={{ socket, isConnected }}>
|
||||
{children}
|
||||
</SocketContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useSocket = () => {
|
||||
const context = useContext(SocketContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useSocket must be used within a SocketProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user