From dbb5f858bc32a1ebc3ef1f3c86e1e96ca811ecac Mon Sep 17 00:00:00 2001 From: karishmas6 Date: Fri, 21 Jun 2024 22:17:46 +0530 Subject: [PATCH] feat: socket context --- src/context/socket.tsx | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/context/socket.tsx diff --git a/src/context/socket.tsx b/src/context/socket.tsx new file mode 100644 index 00000000..c930019d --- /dev/null +++ b/src/context/socket.tsx @@ -0,0 +1,51 @@ +import React, { createContext, useCallback, useContext, useMemo, useState } from 'react'; +import { io, Socket } from 'socket.io-client'; + +const SERVER_ENDPOINT = 'http://localhost:8080'; + +interface SocketState { + socket: Socket | null; + id: string; + setId: (id: string) => void; +}; + +class SocketStore implements Partial{ + socket = null; + id = ''; +}; + +const socketStore = new SocketStore(); +const socketStoreContext = createContext(socketStore as SocketState); + +export const useSocketStore = () => useContext(socketStoreContext); + +export const SocketProvider = ({ children }: { children: JSX.Element }) => { + const [socket, setSocket] = useState(socketStore.socket); + const [id, setActiveId] = useState(socketStore.id); + + const setId = useCallback((id: string) => { + const socket = + io(`${SERVER_ENDPOINT}/${id}`, { + transports: ["websocket"], + rejectUnauthorized: false + }); + + socket.on('connect', () => console.log('connected to socket')); + socket.on("connect_error", (err) => console.log(`connect_error due to ${err.message}`)); + + setSocket(socket); + setActiveId(id); + }, [setSocket]); + + return ( + + {children} + + ); +};