From 8759c55eee3e2b8d42640ec99f01060452e0a901 Mon Sep 17 00:00:00 2001 From: Mitchell McCaffrey Date: Thu, 19 Mar 2020 12:59:01 +1100 Subject: [PATCH] Fixed bug with videos getting deleted when there is more than one --- src/helpers/useSession.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/helpers/useSession.js b/src/helpers/useSession.js index 170a74b..b275abe 100644 --- a/src/helpers/useSession.js +++ b/src/helpers/useSession.js @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useEffect, useState, useRef } from "react"; import Peer from "peerjs"; const getUserMedia = @@ -11,6 +11,8 @@ function useSession(onConnectionOpen, onConnectionSync) { const [peer, setPeer] = useState(null); const [connections, setConnections] = useState({}); const [streams, setStreams] = useState({}); + // Keep a ref to the streams in order to clean them up on unmount + const streamsRef = useRef(streams); function addConnection(connection) { setConnections(prevConnnections => ({ @@ -28,18 +30,20 @@ function useSession(onConnectionOpen, onConnectionSync) { useEffect(() => { setPeer(new Peer()); - }, []); - // Clean up stream on dismount - useEffect(() => { return () => { - for (let stream of Object.values(streams)) { + for (let stream of Object.values(streamsRef.current)) { for (let track of stream.getTracks()) { track.stop(); } } }; - }, [streams]); + }, []); + + // Update stream refs + useEffect(() => { + streamsRef.current = streams; + }, [streams, streamsRef]); useEffect(() => { function handleOpen(id) { @@ -135,8 +139,6 @@ function useSession(onConnectionOpen, onConnectionSync) { } }); - console.log(streams); - const call = peer.call(connectionId, streams[peerId]); call.on("stream", remoteStream => { addStream(remoteStream, connectionId);