Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Created May 20, 2023 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryhouse/42cca17800a3ab6db3cdf99509ee3536 to your computer and use it in GitHub Desktop.
Save coryhouse/42cca17800a3ab6db3cdf99509ee3536 to your computer and use it in GitHub Desktop.
useHasCamera custom hook
import { useEffect, useState } from "react";
type Cameras = {
back: boolean;
front: boolean;
};
/** Returns a device's cameras and their location */
export default function useHasCamera() {
const [cameras, setCameras] = useState<Cameras | null>(null);
useEffect(() => {
const detectCamera = async () => {
let hasRearCamera: boolean;
let hasFrontCamera: boolean;
try {
await navigator.mediaDevices.getUserMedia({
video: { facingMode: { exact: "environment" } },
});
} catch {
hasRearCamera = false;
}
try {
await navigator.mediaDevices.getUserMedia({
video: { facingMode: { exact: "user" } },
});
} catch {
hasFrontCamera = false;
}
setCameras({
back: hasRearCamera,
front: hasFrontCamera,
});
};
detectCamera();
}, []);
return cameras;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment