on 98d950d help sign in
bridge/src/lib/useMailer.js
46 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(
30 async (email, ticket, sender, message, rawTx) => {
31 if (STUB_MAILER) {
32 console.log(`${email} - ${ticket}`);
33 await timeout(Math.random() * 1000); // simulate request with randomness
34 return true;
35 }
37 const success = await sendMail(email, ticket, sender, message, rawTx);
38 if (!success) {
39 throw new Error('Failed to send mail');
40 }
41 },
42 []
43 );
45 return { getHasReceived, sendMail: _sendMail };