Files
memegoat/frontend/src/providers/socket-provider.tsx
Mathis HERRIOT 9db3067721 refactor: improve import order and code formatting
- Reordered and grouped imports consistently in backend and frontend files for better readability.
- Applied indentation and formatting fixes across frontend components, services, and backend modules.
- Adjusted multiline method calls and type definitions for improved clarity.
2026-01-29 14:44:34 +01:00

57 lines
1.3 KiB
TypeScript

"use client";
import * as React from "react";
import { io, type Socket } from "socket.io-client";
import { useAuth } from "./auth-provider";
interface SocketContextType {
socket: Socket | null;
isConnected: boolean;
}
const SocketContext = React.createContext<SocketContextType>({
socket: null,
isConnected: false,
});
export const useSocket = () => React.useContext(SocketContext);
export function SocketProvider({ children }: { children: React.ReactNode }) {
const { isAuthenticated } = useAuth();
const [socket, setSocket] = React.useState<Socket | null>(null);
const [isConnected, setIsConnected] = React.useState(false);
React.useEffect(() => {
if (isAuthenticated) {
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";
const socketInstance = io(apiUrl, {
withCredentials: true,
transports: ["websocket"],
});
socketInstance.on("connect", () => {
setIsConnected(true);
});
socketInstance.on("disconnect", () => {
setIsConnected(false);
});
setSocket(socketInstance);
return () => {
socketInstance.disconnect();
};
} else {
setSocket(null);
setIsConnected(false);
}
}, [isAuthenticated]);
return (
<SocketContext.Provider value={{ socket, isConnected }}>
{children}
</SocketContext.Provider>
);
}