-
Notifications
You must be signed in to change notification settings - Fork 6
/
useCaptureQrCode.ts
60 lines (47 loc) · 1.33 KB
/
useCaptureQrCode.ts
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { useState } from 'react';
// selectors
import { useSelectLogger } from '@extension/selectors';
// types
import { ILogger } from '@common/types';
import { IUseCaptureQrCodeState } from './types';
// utils
import { captureQrCode } from './utils';
export default function useCaptureQrCode(): IUseCaptureQrCodeState {
const logger: ILogger = useSelectLogger();
const [scanning, setScanning] = useState<boolean>(false);
const [url, setUrl] = useState<string | null>(null);
const captureAction: () => void = () => {
let capturedUrl: string;
let intervalId: number;
setScanning(true);
(async () => {
try {
capturedUrl = await captureQrCode();
setUrl(capturedUrl);
setScanning(false);
return;
} catch (error) {
logger.debug(error.message);
}
// add a one second interval that attempts to capture a qr code on the screen
intervalId = window.setInterval(async () => {
if (capturedUrl) {
window.clearInterval(intervalId);
return;
}
try {
capturedUrl = await captureQrCode();
setUrl(capturedUrl);
setScanning(false);
} catch (error) {
logger.debug(error.message);
}
}, 3000);
})();
};
return {
captureAction,
scanning,
url,
};
}