-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathuseCameraDevices.ts
More file actions
37 lines (34 loc) · 1.21 KB
/
useCameraDevices.ts
File metadata and controls
37 lines (34 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { useEffect, useRef, useState } from 'react'
import type { CameraDevice } from '../types/CameraDevice'
import { CameraDevices } from '../CameraDevices'
/**
* Get all available Camera Devices this phone has.
*
* Camera Devices attached to this phone (`back` or `front`) are always available,
* while `external` devices might be plugged in or out at any point,
* so the result of this function might update over time.
*/
export function useCameraDevices(): CameraDevice[] {
const [devices, setDevices] = useState(() => CameraDevices.getAvailableCameraDevices())
const numberOfDevicesRef = useRef(devices.length)
useEffect(() => {
let isMounted = true
const listener = CameraDevices.addCameraDevicesChangedListener((newDevices) => {
setDevices(newDevices)
})
// Only update if we got new devices and the component is still mounted
// This happens with Android only
if (numberOfDevicesRef.current === 0) {
CameraDevices.getAvailableCameraDevicesManually().then((newDevices) => {
if (isMounted && newDevices.length > 0) {
setDevices(newDevices)
}
})
}
return () => {
isMounted = false
listener.remove()
}
}, [])
return devices
}