Home > Back-end >  Avoid to make Socket.io connection twice
Avoid to make Socket.io connection twice

Time:06-05

I am using react at frontend and express on backend

I wrote the following code to connect client to backend

import React, { useEffect,useState} from 'react'
import { io } from "socket.io-client"
const Video = () => {
    const [socket,setSocket] = useState(io("http://localhost:3001"));
    const myVideo = document.createElement('video')
    myVideo.muted = true;

    useEffect(() => {
        navigator.mediaDevices.getUserMedia({
            video: true,
            audio: true
        }).then(stream => {
            addVideoStream(myVideo, stream)

        })
    }, [])

But the socket onconnection event fired twice for a single webpage opening. Please tell me where is the problem, what i add or remove to make only one connection per user .

CodePudding user response:

try a useRef for debugging to see if strict mode is the problem:

import { useEffect, useState, useRef } from 'react'

export default function App() {
  const secondRender = useRef(false)
  const [count, setCount] = useState(0)
  useEffect(()=> {
    secondRender.current && setCount(count => count  1)
    secondRender.current = true
  },[])
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {count}
    </div>
  );
}

here you will see that the count stays at 1, so the functin in useEffect is only fired once

CodePudding user response:

Pretty quickly here is an idea... it might be a bit falsy because i haven't tried it out, but the idea here is to extract you io call into a custom hook, and implement a condition so that your call is not called twice. You can probably improve this with a loader condition that does not return your socket if the call hasn't been successfull etc..

import { useState, useEffect, useRef } from 'react

const useIo = () => {
 const isSecondRender = useRef(false)
 const [socket, setSocket] = useState (null) 

 useEffect (()=>{
  isSecondRender.current && setSocket(io("http://localhost:3001"))
  isSecondRender.current = true
 },[])
 
 return socket
}
``` javascript
  • Related