Created
May 20, 2023 19:18
-
-
Save coryhouse/42cca17800a3ab6db3cdf99509ee3536 to your computer and use it in GitHub Desktop.
useHasCamera custom hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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