From ef7423911f3f19a8c41338f70d4c1f150caa8d80 Mon Sep 17 00:00:00 2001 From: sangram Date: Sun, 2 Jun 2024 01:08:05 +0530 Subject: [PATCH] Fixed useEffect dependencies in useMediaRecorder hook --- packages/react/src/hooks/useMediaRecorder.js | 50 ++++++++++++++------ 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/packages/react/src/hooks/useMediaRecorder.js b/packages/react/src/hooks/useMediaRecorder.js index 05046a59d..97d2220a0 100644 --- a/packages/react/src/hooks/useMediaRecorder.js +++ b/packages/react/src/hooks/useMediaRecorder.js @@ -1,7 +1,8 @@ -import { useState, useRef } from 'react'; +import { useState, useRef, useEffect } from 'react'; function useUserMedia(constraints, videoRef) { - const [stream, setStream] = useState(); + const [stream, setStream] = useState(null); + async function getStream(refresh = false) { if (stream && !refresh) { return stream; @@ -16,26 +17,45 @@ function useUserMedia(constraints, videoRef) { return _stream; } + return { stream, getStream }; } export function useMediaRecorder({ constraints, onStop, videoRef }) { - const [recorder, setRecorder] = useState(); - const { getStream } = useUserMedia(constraints, videoRef); + const [recorder, setRecorder] = useState(null); + const { stream, getStream } = useUserMedia(constraints, videoRef); const chunks = useRef([]); + useEffect(() => { + async function initializeRecorder() { + if (!stream) return; + + chunks.current = []; + const _recorder = new MediaRecorder(stream); + _recorder.start(); + setRecorder(_recorder); + + _recorder.addEventListener('dataavailable', (event) => { + chunks.current.push(event.data); + }); + + _recorder.addEventListener('stop', () => { + onStop && onStop(chunks.current); + }); + } + + initializeRecorder(); + + return () => { + if (recorder) { + recorder.stop(); + stream.getTracks().forEach((track) => track.stop()); + } + }; + }, [constraints, onStop, recorder, stream, videoRef]); + async function start() { - const stream = await getStream(constraints, true); - chunks.current = []; - const _recorder = new MediaRecorder(stream); - _recorder.start(); - setRecorder(_recorder); - _recorder.addEventListener('dataavailable', (event) => { - chunks.current.push(event.data); - }); - _recorder.addEventListener('stop', () => { - onStop && onStop(chunks.current); - }); + await getStream(true); } async function stop() {