UNPKG

@duongtrungnguyen/next-helper

Version:
38 lines 1.31 kB
"use client"; import { useEffect, useRef, useState } from "react"; import { io } from "socket.io-client"; import { cookies } from "next/headers"; import { libConfig } from "../configs"; import { useAuth } from "../auth"; function useSocket(namespace) { const { state } = useAuth(); const socketRef = useRef(null); const [isConnected, setIsConnected] = useState(false); useEffect(() => { initSocket(); return () => { var _a; (_a = socketRef.current) == null ? void 0 : _a.disconnect(); }; }, [namespace, state]); const initSocket = async () => { var _a; const cookieStore = await cookies(); const accessToken = (_a = cookieStore.get(libConfig.auth.cookies.accessToken)) == null ? void 0 : _a.value; if (!accessToken || !state.isAuthenticated) return; if (socketRef.current) { socketRef.current.disconnect(); } socketRef.current = io(`${process.env.NEXT_PUBLIC_API_SERVER_ORIGIN}/${namespace}`, { transports: ["websocket"], auth: { token: `Bearer ${accessToken}` } }); socketRef.current.on("connect", () => setIsConnected(true)); socketRef.current.on("disconnect", () => setIsConnected(false)); }; return { socket: socketRef.current, isConnected }; } export { useSocket }; //# sourceMappingURL=use-socket.js.map