sandbox-web-ide/frontend/context/SocketContext.tsx

66 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2024-10-21 13:57:45 -06:00
"use client"
2024-10-21 13:57:45 -06:00
import React, { createContext, useContext, useEffect, useState } from "react"
import { io, Socket } from "socket.io-client"
interface SocketContextType {
2024-10-21 13:57:45 -06:00
socket: Socket | null
setUserAndSandboxId: (userId: string, sandboxId: string) => void
}
2024-10-21 13:57:45 -06:00
const SocketContext = createContext<SocketContextType | undefined>(undefined)
2024-10-21 13:57:45 -06:00
export const SocketProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [socket, setSocket] = useState<Socket | null>(null)
const [userId, setUserId] = useState<string | null>(null)
const [sandboxId, setSandboxId] = useState<string | null>(null)
useEffect(() => {
if (userId && sandboxId) {
2024-10-21 13:57:45 -06:00
console.log("Initializing socket connection...")
const newSocket = io(
`${process.env.NEXT_PUBLIC_SERVER_URL}?userId=${userId}&sandboxId=${sandboxId}`
)
console.log("Socket instance:", newSocket)
setSocket(newSocket)
2024-10-21 13:57:45 -06:00
newSocket.on("connect", () => {
console.log("Socket connected:", newSocket.id)
})
2024-10-21 13:57:45 -06:00
newSocket.on("disconnect", () => {
console.log("Socket disconnected")
})
return () => {
2024-10-21 13:57:45 -06:00
console.log("Disconnecting socket...")
newSocket.disconnect()
}
}
2024-10-21 13:57:45 -06:00
}, [userId, sandboxId])
const setUserAndSandboxId = (newUserId: string, newSandboxId: string) => {
2024-10-21 13:57:45 -06:00
setUserId(newUserId)
setSandboxId(newSandboxId)
}
const value = {
socket,
setUserAndSandboxId,
2024-10-21 13:57:45 -06:00
}
return (
2024-10-21 13:57:45 -06:00
<SocketContext.Provider value={value}>{children}</SocketContext.Provider>
)
}
export const useSocket = (): SocketContextType => {
2024-10-21 13:57:45 -06:00
const context = useContext(SocketContext)
if (!context) {
2024-10-21 13:57:45 -06:00
throw new Error("useSocket must be used within a SocketProvider")
}
2024-10-21 13:57:45 -06:00
return context
}