Skip to content

Instantly share code, notes, and snippets.

@Withoutbytes
Created November 27, 2021 11:07
Show Gist options
  • Save Withoutbytes/a4965a5953068355fc5d37d4cfc43026 to your computer and use it in GitHub Desktop.
Save Withoutbytes/a4965a5953068355fc5d37d4cfc43026 to your computer and use it in GitHub Desktop.

Revisions

  1. Withoutbytes created this gist Nov 27, 2021.
    56 changes: 56 additions & 0 deletions useSocketIO.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    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];
    }