Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed useEffect dependencies in useMediaRecorder hook #582

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 35 additions & 15 deletions packages/react/src/hooks/useMediaRecorder.js
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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() {
Expand Down
Loading