Last active
February 12, 2022 18:10
-
-
Save sidwebworks/926c7e387847936d6aa6e94e9673312c to your computer and use it in GitHub Desktop.
A hook system for managing socket.io client connections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContext, useContext, useMemo, useRef } from 'react'; | |
import { io } from 'socket.io-client'; | |
const DEFAULT = { | |
namespace: '/', | |
baseUri: process.env.NEXT_PUBLIC_SOCKET_IO_URI, | |
}; | |
const createSocket = (nsp, conf = {}) => { | |
return io(new URL(nsp, DEFAULT.baseUri).href, conf); | |
}; | |
export const useSocket = () => useContext(IO_CONTEXT); | |
const IO_CONTEXT = createContext({}); | |
export const SocketProvider = ({ children }) => { | |
const sockets = useRef({}); | |
const getConnection = (nsp) => sockets.current?.[nsp]; | |
const getAllConnections = () => sockets.current; | |
const createConnection = (nsp = DEFAULT.namespace, opts) => { | |
const cleanUp = () => { | |
const old = sockets.current?.[nsp]; | |
if (old) { | |
old.disconnect(); | |
old.removeAllListeners(); | |
delete sockets.current[nsp]; | |
} | |
}; | |
const exists = sockets.current[nsp]; | |
if (exists) { | |
console.log('Already opened'); | |
if (exists.disconnected) { | |
exists.connect(); | |
} | |
return { socket: exists, cleanUp }; | |
} | |
console.log('Try to connect'); | |
const socket = createSocket(nsp, opts); | |
sockets.current[nsp] = socket; | |
return { | |
socket, | |
cleanUp, | |
}; | |
}; | |
const values = useMemo( | |
() => ({ createConnection, getConnection, getAllConnections }), | |
[] | |
); | |
return <IO_CONTEXT.Provider value={values}>{children}</IO_CONTEXT.Provider>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment