Browse Source

Allow to reconnect after deconnection

Jeremie Pardou-Piquemal 3 years ago
parent
commit
9e596717a8
3 changed files with 17 additions and 6 deletions
  1. 3 3
      package-lock.json
  2. 1 1
      package.json
  3. 13 2
      src/hooks/useC2C.jsx

+ 3 - 3
package-lock.json

@@ -6494,9 +6494,9 @@
       }
     },
     "client2client.io": {
-      "version": "2.0.1",
-      "resolved": "https://registry.npmjs.org/client2client.io/-/client2client.io-2.0.1.tgz",
-      "integrity": "sha512-9BZtxrLQPpCKm6OhBDAcQWBjyawomfUAvNYqwc6pk+m5KG9wbx0C0uIz0kP0SBWmSjwheYCNBZv+c3Ta3tyzpQ==",
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/client2client.io/-/client2client.io-2.0.2.tgz",
+      "integrity": "sha512-iLLz/SSFzfWdXg4yZm5EQt+HdgfcrlbrrBB5qCNxOy/Lnuzf3NKn2nOWCPTplZaUyP1NMy/3fgSV7yrlXBmXYQ==",
       "requires": {
         "nanoid": "^3.1.20"
       },

+ 1 - 1
package.json

@@ -8,7 +8,7 @@
     "@welldone-software/why-did-you-render": "^4.2.5",
     "body-parser": "^1.19.0",
     "chota": "^0.8.0",
-    "client2client.io": "^2.0.1",
+    "client2client.io": "^2.0.2",
     "color2k": "^1.0.0-rc.5",
     "dayjs": "^1.10.4",
     "diacritic": "0.0.2",

+ 13 - 2
src/hooks/useC2C.jsx

@@ -14,6 +14,14 @@ export const C2CProvider = ({ room, channel = "default", children }) => {
   const [isMaster, setIsMaster] = React.useState(false);
   const [c2c, setC2c] = React.useState(null);
   const roomRef = React.useRef(null);
+  const mountedRef = React.useRef(false);
+
+  React.useEffect(() => {
+    mountedRef.current = true;
+    return () => {
+      mountedRef.current = false;
+    };
+  }, []);
 
   if (!contextMap[channel]) {
     contextMap[channel] = React.createContext({
@@ -21,12 +29,12 @@ export const C2CProvider = ({ room, channel = "default", children }) => {
       isMaster: false,
     });
   }
-
   const Context = contextMap[channel];
 
   React.useEffect(() => {
     const disconnect = () => {
       console.log(`Disconnected from ${channel}…`);
+      if (!mountedRef.current) return;
       setJoined(false);
       setIsMaster(false);
     };
@@ -38,6 +46,7 @@ export const C2CProvider = ({ room, channel = "default", children }) => {
   }, [channel, socket]);
 
   React.useEffect(() => {
+    // Connect
     if (!socket) {
       return;
     }
@@ -49,17 +58,19 @@ export const C2CProvider = ({ room, channel = "default", children }) => {
       room,
       onMaster: () => {
         console.log(`Is now master on channel ${channel}…`);
+        if (!mountedRef.current) return;
         setIsMaster(true);
       },
       onJoined: (newRoom) => {
         console.log(`Connected on channel ${channel}…`);
         roomRef.current = newRoom;
 
+        if (!mountedRef.current) return;
         setC2c(newRoom);
-
         setJoined(true);
       },
     });
+
     return () => {
       roomRef.current.leave();
     };