Sfoglia il codice sorgente

add socket setup method

Yuken Tezuka 3 anni fa
parent
commit
b2e81a6e47
1 ha cambiato i file con 28 aggiunte e 9 eliminazioni
  1. 28 9
      packages/app/src/stores/websocket.tsx

+ 28 - 9
packages/app/src/stores/websocket.tsx

@@ -1,9 +1,12 @@
-import { SWRResponse } from 'swr';
+import { useEffect } from 'react';
+
 import io, { Socket } from 'socket.io-client';
+import { SWRResponse } from 'swr';
 
-import { useStaticSWR } from './use-static-swr';
 import loggerFactory from '~/utils/logger';
 
+import { useStaticSWR } from './use-static-swr';
+
 const logger = loggerFactory('growi:stores:ui');
 
 export const GLOBAL_SOCKET_NS = '/';
@@ -15,15 +18,21 @@ export const GLOBAL_ADMIN_SOCKET_KEY = 'globalAdminSocket';
 /*
  * Global Socket
  */
-export const useSetupGlobalSocket = (): SWRResponse<Socket, Error> => {
-  const socket = io(GLOBAL_SOCKET_NS, {
-    transports: ['websocket'],
-  });
+export const useSetupGlobalSocket = (): void => {
+
+  const { mutate } = useStaticSWR(GLOBAL_SOCKET_KEY);
 
-  socket.on('error', (err) => { logger.error(err) });
-  socket.on('connect_error', (err) => { logger.error('Failed to connect with websocket.', err) });
+  useEffect(() => {
+    const socket = io(GLOBAL_SOCKET_NS, {
+      transports: ['websocket'],
+    });
 
-  return useStaticSWR(GLOBAL_SOCKET_KEY, socket);
+    socket.on('error', (err) => { logger.error(err) });
+    socket.on('connect_error', (err) => { logger.error('Failed to connect with websocket.', err) });
+
+    mutate(socket);
+
+  }, [mutate]);
 };
 
 export const useGlobalSocket = (): SWRResponse<Socket, Error> => {
@@ -51,3 +60,13 @@ export const useSetupGlobalAdminSocket = (shouldInit: boolean): SWRResponse<Sock
 export const useGlobalAdminSocket = (): SWRResponse<Socket, Error> => {
   return useStaticSWR(GLOBAL_ADMIN_SOCKET_KEY);
 };
+
+export const useSetupGlobalSocketForPage = (pageId: string | undefined): void => {
+  const { data: socket } = useGlobalSocket();
+
+  useEffect(() => {
+    if (socket == null || pageId == null) { return }
+
+    socket.emit('join:page', { socketId: socket.id, pageId });
+  }, [pageId, socket]);
+};