-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathusePreflightTest.ts
More file actions
53 lines (44 loc) · 1.82 KB
/
usePreflightTest.ts
File metadata and controls
53 lines (44 loc) · 1.82 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import React, { useCallback, useRef } from 'react';
import { ACTIONTYPE } from '../AppStateProvider';
import axios from 'axios';
import { PreflightTest, runPreflight } from 'twilio-video';
import { GetRecaptchaToken } from '../../../RecaptchaProvider';
export default function usePreflightTest(dispatch: React.Dispatch<ACTIONTYPE>, getRecaptchaToken?: GetRecaptchaToken) {
const preflightTestRef = useRef<PreflightTest>();
const startPreflightTest = useCallback(() => {
// Don't start a new preflight test if one is already running
if (preflightTestRef.current) {
return;
}
dispatch({ type: 'preflight-started' });
const tokenPromise = getRecaptchaToken
? getRecaptchaToken('preflight').then((recaptchaToken) =>
axios('app/token', {
headers: recaptchaToken ? { 'X-Recaptcha-Token': recaptchaToken } : {},
})
)
: axios('app/token');
return tokenPromise
.then((response) => {
const preflightTest = runPreflight(response.data.token);
preflightTestRef.current = preflightTest;
preflightTest.on('progress', (progress) => {
dispatch({ type: 'preflight-progress', progress });
});
preflightTest.on('completed', (report) => {
dispatch({ type: 'preflight-completed', report });
dispatch({ type: 'preflight-finished' });
});
preflightTest.on('failed', (error) => {
dispatch({ type: 'preflight-failed', error });
dispatch({ type: 'preflight-finished' });
});
})
.catch((error) => {
console.error('Error running the preflight test', error);
dispatch({ type: 'preflight-token-failed', error });
dispatch({ type: 'preflight-finished' });
});
}, [dispatch, getRecaptchaToken]);
return { startPreflightTest } as const;
}