live updates
This commit is contained in:
91
frontend/src/SocketContext.jsx
Normal file
91
frontend/src/SocketContext.jsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { io } from 'socket.io-client';
|
||||
import { useAuth } from './AuthContext';
|
||||
|
||||
const SocketContext = createContext();
|
||||
|
||||
export function useSocket() {
|
||||
const context = useContext(SocketContext);
|
||||
if (!context) {
|
||||
throw new Error('useSocket must be used within SocketProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
export function SocketProvider({ children }) {
|
||||
const [socket, setSocket] = useState(null);
|
||||
const [connected, setConnected] = useState(false);
|
||||
const { user, token } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
// Only connect if user is authenticated
|
||||
if (!user || !token) {
|
||||
if (socket) {
|
||||
socket.disconnect();
|
||||
setSocket(null);
|
||||
setConnected(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine backend URL
|
||||
const backendUrl = import.meta.env.VITE_API_URL ||
|
||||
(import.meta.env.DEV ? 'http://localhost:4000' : window.location.origin);
|
||||
|
||||
// Create socket connection with JWT authentication
|
||||
const newSocket = io(backendUrl, {
|
||||
auth: {
|
||||
token
|
||||
},
|
||||
reconnection: true,
|
||||
reconnectionAttempts: 5,
|
||||
reconnectionDelay: 1000
|
||||
});
|
||||
|
||||
newSocket.on('connect', () => {
|
||||
console.log('🔌 Socket connected');
|
||||
setConnected(true);
|
||||
});
|
||||
|
||||
newSocket.on('disconnect', () => {
|
||||
console.log('❌ Socket disconnected');
|
||||
setConnected(false);
|
||||
});
|
||||
|
||||
newSocket.on('connect_error', (error) => {
|
||||
console.error('Socket connection error:', error.message);
|
||||
});
|
||||
|
||||
setSocket(newSocket);
|
||||
|
||||
// Cleanup on unmount
|
||||
return () => {
|
||||
newSocket.disconnect();
|
||||
};
|
||||
}, [user, token]);
|
||||
|
||||
const joinChallenge = (challengeId) => {
|
||||
if (socket && connected) {
|
||||
socket.emit('join:challenge', challengeId);
|
||||
}
|
||||
};
|
||||
|
||||
const leaveChallenge = (challengeId) => {
|
||||
if (socket && connected) {
|
||||
socket.emit('leave:challenge', challengeId);
|
||||
}
|
||||
};
|
||||
|
||||
const value = {
|
||||
socket,
|
||||
connected,
|
||||
joinChallenge,
|
||||
leaveChallenge
|
||||
};
|
||||
|
||||
return (
|
||||
<SocketContext.Provider value={value}>
|
||||
{children}
|
||||
</SocketContext.Provider>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user