diff --git a/components/WebCam/WebCam.tsx b/components/WebCam/WebCam.tsx index c505993..0fd61a5 100644 --- a/components/WebCam/WebCam.tsx +++ b/components/WebCam/WebCam.tsx @@ -1,47 +1,7 @@ -import handleTxError from "@/lib/handleTxError" import { usePageLoad } from "@/providers/PageLoadProvider" -import { useEffect, useRef, useState } from "react" const WebCam = () => { - const { granted, setGranted } = usePageLoad() - const [stream, setStream] = useState(null) - const videoRef = useRef(null) - - const onClick = async () => { - try { - const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }) - setStream(mediaStream) - setGranted(true) - } catch (error) { - handleTxError(error) - } - } - - useEffect(() => { - const init = async () => { - let mediaStream = null - if (granted) { - mediaStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }) - setStream(mediaStream) - } - - if (!stream && !mediaStream) return - - videoRef.current.srcObject = stream || mediaStream - videoRef.current.muted = true - videoRef.current.play() - } - - if (!videoRef?.current) return - - init() - // eslint-disable-next-line consistent-return - return () => { - if (stream) { - stream.getTracks().forEach((track) => track.stop()) - } - } - }, [stream, granted, videoRef]) + const { granted, grantCamera, videoRef } = usePageLoad() return (
@@ -49,14 +9,12 @@ const WebCam = () => { )} - {granted && ( -
) } diff --git a/providers/PageLoadProvider.tsx b/providers/PageLoadProvider.tsx index 7562df4..8b8c6e5 100644 --- a/providers/PageLoadProvider.tsx +++ b/providers/PageLoadProvider.tsx @@ -1,5 +1,6 @@ import useLiveTime from "@/hooks/useLiveTime" -import { createContext, useContext, useMemo, useState } from "react" +import handleTxError from "@/lib/handleTxError" +import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react" const PageLoadContext = createContext(null) @@ -7,6 +8,26 @@ const PageLoadProvider = ({ children }) => { const [entered, setEntered] = useState(false) const { liveTime } = useLiveTime() const [granted, setGranted] = useState(false) + const [stream, setStream] = useState(null) + const videoRef = useRef(null) + + const grantCamera = async () => { + try { + const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }) + setStream(mediaStream) + setGranted(true) + } catch (error) { + handleTxError(error) + } + } + + useEffect(() => { + if (stream) { + videoRef.current.srcObject = stream + videoRef.current.muted = true + videoRef.current.play() + } + }, [stream, videoRef?.current]) const value = useMemo( () => ({ @@ -15,8 +36,12 @@ const PageLoadProvider = ({ children }) => { liveTime, setGranted, granted, + stream, + setStream, + grantCamera, + videoRef, }), - [entered, setEntered, liveTime, granted, setGranted], + [entered, setEntered, liveTime, granted, setGranted, stream, setStream, grantCamera, videoRef], ) return {children}