-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuse-video-stream.ts
40 lines (32 loc) · 980 Bytes
/
use-video-stream.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import * as React from 'react';
export function useVideoStream() {
const videoElementRef = React.useRef<HTMLVideoElement>(null);
const [error, setError] = React.useState<Error | null>(null);
const [retryCount, setRetryCount] = React.useState<number>(0);
React.useEffect(() => {
async function startVideo() {
if (videoElementRef.current === null) return;
try {
const mediaStream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: 'environment',
},
audio: false,
});
videoElementRef.current.srcObject = mediaStream;
setError(null);
} catch (error) {
if (error instanceof Error) {
setError(error);
}
console.error(error);
}
}
startVideo();
}, [retryCount]);
const retry = () => {
setError(null);
setRetryCount((count) => count + 1);
};
return [videoElementRef, { error, retry }] as const;
}