Created
November 27, 2021 11:07
-
-
Save Withoutbytes/a4965a5953068355fc5d37d4cfc43026 to your computer and use it in GitHub Desktop.
Use socket.io-client for react / next.js with lastMessage system and emit with auto cleanup.
This file contains hidden or 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 { useEffect, useState } from "react"; | |
| import { io, ManagerOptions, Socket, SocketOptions } from "socket.io-client"; | |
| export const useSocketIO = ( | |
| uri?: string | Partial<ManagerOptions & SocketOptions>, | |
| opts?: Partial<ManagerOptions & SocketOptions> | |
| ): [Socket] => { | |
| const [activeSocket, setActiveSocket] = useState<Socket>(null); | |
| useEffect(() => { | |
| const socket = io(uri, opts); | |
| const onConnect = () => { | |
| setActiveSocket(socket); | |
| }; | |
| const onDisconnect = () => { | |
| setActiveSocket(null); | |
| }; | |
| socket.on("connect", onConnect); | |
| socket.on("disconnect", onDisconnect); | |
| return () => { | |
| socket.removeListener("disconnect", onDisconnect); | |
| socket.removeListener("connect", onConnect); | |
| socket.disconnect(); | |
| }; | |
| }, []); | |
| return [activeSocket]; | |
| }; | |
| export function useEventIO<TypeData>( | |
| socket: Socket, | |
| eventName: string | |
| ): [TypeData, (...args: any[]) => void] { | |
| const [lastEvent, setLastEvent] = useState<TypeData>(null); | |
| const emit = (...args: any[]) => { | |
| if (!socket) { | |
| throw new Error("Socket is not defined"); | |
| } | |
| socket.emit(eventName, ...args); | |
| }; | |
| useEffect(() => { | |
| if (!socket) return; | |
| socket.on(eventName, setLastEvent); | |
| return () => { | |
| socket.removeListener(eventName, setLastEvent); | |
| }; | |
| }, [socket]); | |
| return [lastEvent, emit]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment