'React webcam error on stop and time limit

const handleStartCaptureClick = React.useCallback(() => {
        setCapturing(true);
        // setStillRecording(true);
        setStillRecording(prev => (prev, true));
        imgSrc.current = webcamRef.current.getScreenshot({
            width: 190,
            height: 120
          });
        mediaRecorderRef.current = new MediaRecorder(webcamRef.current.stream, {
          mimeType: "video/webm"
        });
        mediaRecorderRef.current.addEventListener(
          "dataavailable",
          handleDataAvailable
        );
        mediaRecorderRef.current.start();
        setTimeout(() => {
            handleStopCaptureClick();
        }, 5000);
      }, [webcamRef, setCapturing, mediaRecorderRef]);
      const handleDataAvailable = React.useCallback(
        ({ data }) => {
          if (data.size > 0) {
            setRecordedChunks((prev) => prev.concat(data));
          }
        },
        [setRecordedChunks]
      );
      const handleStopCaptureClick = React.useCallback(() => {
        setStillRecording(false);
        mediaRecorderRef.current.stop();
        setCapturing(false);
      }, [mediaRecorderRef, webcamRef, capturing]);

    const handlePreview = React.useCallback(async () => {
        setShowVideo(true);
        setOpen(false);
        if (recordedChunks.length) {
            const blob = new Blob(recordedChunks, {
                type: "video/webm"
                });
            const url = URL.createObjectURL(blob);
            setUrl(url);
            setVideoBlob(blob);
        }
    }, [recordedChunks, Url]);

Hi, I have written the above code for start and stop of recording using webcam. I need to code in a way that it should stop after a time limit or if i click on stop button. I am able to do it separately but am getting an error if start and stop before the time limit. "× InvalidStateError: Failed to execute 'stop' on 'MediaRecorder': The MediaRecorder's state is 'inactive'."



Solution 1:[1]

slightly changing your timeout code

setTimeout(() => { setStillRecording(false); mediaRecorderRef.current.stop(); setCapturing(false); }, 5000);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leonardo Alves Machado