From 8d647eaeffa52715ec3a45562da6685ebda11eab Mon Sep 17 00:00:00 2001 From: Kalle <38327916+Sendouc@users.noreply.github.com> Date: Tue, 29 Mar 2022 23:40:08 +0300 Subject: [PATCH] Use React Context for sharing socket --- app/hooks/useSocketEvent.ts | 11 ++++++----- app/root.tsx | 16 +++++++++++++++- app/utils/socketContext.tsx | 18 ++++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) create mode 100644 app/utils/socketContext.tsx diff --git a/app/hooks/useSocketEvent.ts b/app/hooks/useSocketEvent.ts index 2af9d4d30..c2cc4d424 100644 --- a/app/hooks/useSocketEvent.ts +++ b/app/hooks/useSocketEvent.ts @@ -1,15 +1,16 @@ -import io from "socket.io-client"; import * as React from "react"; +import { useSocket } from "~/utils/socketContext"; // eslint-disable-next-line @typescript-eslint/no-explicit-any export function useSocketEvent(event: string, handler: (data: any) => void) { - React.useEffect(() => { - const socket = io(); + const socket = useSocket(); + React.useEffect(() => { + if (!socket) return; socket.on(event, handler); return () => { - socket.close(); + socket.off(event); }; - }, [handler]); + }, [socket, handler]); } diff --git a/app/root.tsx b/app/root.tsx index 2d1116bfd..27999d0b7 100644 --- a/app/root.tsx +++ b/app/root.tsx @@ -17,6 +17,8 @@ import resetStyles from "~/styles/reset.css"; import globalStyles from "~/styles/global.css"; import layoutStyles from "~/styles/layout.css"; import { DISCORD_URL } from "./constants"; +import { io, Socket } from "socket.io-client"; +import { SocketProvider } from "./utils/socketContext"; export const links: LinksFunction = () => { return [ @@ -52,12 +54,24 @@ export const loader: LoaderFunction = ({ context }) => { export const unstable_shouldReload = () => false; export default function App() { + const [socket, setSocket] = React.useState(); + const children = React.useMemo(() => , []); const data = useLoaderData(); + React.useEffect(() => { + const socket = io(); + setSocket(socket); + return () => { + socket.close(); + }; + }, []); + return ( - {children} + + {children} + ); } diff --git a/app/utils/socketContext.tsx b/app/utils/socketContext.tsx new file mode 100644 index 000000000..3074eff88 --- /dev/null +++ b/app/utils/socketContext.tsx @@ -0,0 +1,18 @@ +import type { ReactNode } from "react"; +import { createContext, useContext } from "react"; +import type { Socket } from "socket.io-client"; + +type ProviderProps = { + socket: Socket | undefined; + children: ReactNode; +}; + +const context = createContext(undefined); + +export function useSocket() { + return useContext(context); +} + +export function SocketProvider({ socket, children }: ProviderProps) { + return {children}; +}