| import { useEffect, useRef } from 'react'; | |
| import { io } from 'socket.io-client'; | |
| import { useAuth } from './useAuth'; | |
| export const useSocket = () => { | |
| const { user } = useAuth(); | |
| const socket = useRef(null); | |
| useEffect(() => { | |
| if (user && !socket.current) { | |
| const token = localStorage.getItem('token'); | |
| socket.current = io(process.env.REACT_APP_SOCKET_URL || 'http://localhost:5000', { | |
| auth: { | |
| token | |
| }, | |
| transports: ['websocket'] | |
| }); | |
| socket.current.on('connect', () => { | |
| console.log('Connected to server'); | |
| }); | |
| socket.current.on('disconnect', () => { | |
| console.log('Disconnected from server'); | |
| }); | |
| socket.current.on('connect_error', (error) => { | |
| console.error('Connection error:', error); | |
| }); | |
| } | |
| return () => { | |
| if (socket.current) { | |
| socket.current.disconnect(); | |
| socket.current = null; | |
| } | |
| }; | |
| }, [user]); | |
| return socket.current; | |
| }; |