Roger Staxx
Roger Staxx

Reputation: 439

Take a picture and record video react native

My goal is to record a video when holding down the camera button but also take a picture when tapping the camera button. Any idea what I'm doing wrong?

  const [video, setVideo] = useState(null);
  const [recording, setRecording] = useState(false);

  const cameraRef = createRef();

  const onLongPressButton = () => {
    setRecording(true);
    startRecord();
  };


  const startRecord = async () => {
    setRecording(true);
    console.log("RECORDING");
    if (cameraRef.current) {
      setRecording(true);
      const recordedVideo = await cameraRef.current.recordAsync();
      setVideo(recordedVideo);
    }
  };

  const stopRecord = async () => {
    await cameraRef.current.stopRecording();
    console.log("STOP RECORDING");
    setRecording(false);
  };


  const handlePhoto = async () => {
    if (cameraRef.current && !recording) {
      let photo = await cameraRef.current.takePictureAsync({});
      console.log(photo.uri);
    } else {
      stopRecord();
    }
  };

And here is my camera button component:

<Circle
onPress={handlePhoto}
onLongPress={onLongPressButton}
onPressOut={async () => {
await cameraRef.current.stopRecording();
console.log("STOP RECORDING");
setRecording(false);
}}
delayLongPress={50}
              />

Upvotes: 2

Views: 1235

Answers (1)

Marek Lisik
Marek Lisik

Reputation: 2185

The issue appears to be not with the camera or touch handling, but with the use of createRef instead of useRef. Note that in your case, used within a function component, createRef will create a new ref on every render. Replace it with useRef so that the reference remains the same across renders:

 const cameraRef = useRef();

Upvotes: 1

Related Questions