'WebRTC stream doesn't appear (simple-peer)

I am trying to make a video call using simple-peer and I tried a lot with same code but sometimes I can see what I expected but it doesn't always work well. At first, I tried to manage 'userStream' by useState but setState is asynchronous so I couldn't get the stream. I tweaked that as 'let userStream = null'. I guess this way is not stable as well so it doesn't work sometimes. I don't know what is the problem...

const myVideo = useRef();
  const userVideo = useRef();
  const connectionRef = useRef();
  const roomName = '123';
  let userStream = null;
  let creator = false;

  useEffect(() => {
    const socket = io('https://jg-jg.shop');
    socket.emit('joinRoom', roomName);

    socket.on('created', () => {
      creator = true;

      navigator.mediaDevices
        .getUserMedia({ video: true, audio: true })
        .then((stream) => {
          userStream = stream;
          myVideo.current.srcObject = stream;
          console.log(1);
        });
    });

    socket.on('joined', () => {
      navigator.mediaDevices
        .getUserMedia({ video: true, audio: true })
        .then((stream) => {
          userStream = stream;
          myVideo.current.srcObject = stream;
          console.log(2);
        });

      socket.emit('ready', roomName);
    });

    socket.on('ready', () => {
      if (creator) {
        const peer = new Peer({
          initiator: true,
          trickle: false,
          stream: userStream,
        });

        peer.on('signal', (signal) => {
          socket.emit('sendingSignal', { signal, roomName });
          console.log(3);
        });

        peer.on('stream', (stream) => {
          userVideo.current.srcObject = stream;
          console.log(4);
        });

        socket.on('receivingSignal', (signal) => {
          peer.signal(signal);
          console.log(5);
        });

        connectionRef.current = peer;
      }
    });

    socket.on('offer', (incomingSignal) => {
      if (!creator) {
        const peer = new Peer({
          initiator: false,
          trickle: false,
          stream: userStream,
        });

        peer.on('signal', (signal) => {
          socket.emit('returningSignal', { signal, roomName });
          console.log(6);
        });

        peer.on('stream', (stream) => {
          userVideo.current.srcObject = stream;
          console.log(7);
        });

        peer.signal(incomingSignal);
        console.log(8);
        connectionRef.current = peer;
      }
    });
  }, []);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source