on 3ecbc24 help sign in
bridge/src/lib/useMailer.js
43 lines 1.2 kB history raw
1import { useCallback, useRef } from 'react';
3import { hasReceived, sendMail } from './inviteMail';
4import timeout from './timeout';
6const STUB_MAILER = process.env.REACT_APP_STUB_MAILER === 'true';
8export default function useMailer() {
9 const cache = useRef({});
11 const getHasReceived = useCallback(
12 async email => {
13 if (!cache.current[email]) {
14 if (STUB_MAILER) {
15 await timeout(350); // simulate request
16 cache.current[email] = false;
17 } else {
18 cache.current[email] = await hasReceived(email);
19 }
20 }
22 return cache.current[email];
23 },
24 [cache]
25 );
27 // prefix to avoid clobbering sendMail import
28 // also throws if return value is false
29 const _sendMail = useCallback(async (email, ticket, sender, rawTx) => {
30 if (STUB_MAILER) {
31 console.log(`${email} - ${ticket}`);
32 await timeout(Math.random() * 1000); // simulate request with randomness
33 return true;
34 }
36 const success = await sendMail(email, ticket, sender, rawTx);
37 if (!success) {
38 throw new Error('Failed to send mail');
39 }
40 }, []);
42 return { getHasReceived, sendMail: _sendMail };