all repos — caroster @ 72728bbbc84474c84bf645ef0f29ceeffd807574

[Octree] Group carpool to your event https://caroster.io

frontend/containers/LoginForm/index.tsx (view raw)

 1import {
 2  Button,
 3  FormHelperText,
 4  Stack,
 5  TextField,
 6  Typography,
 7} from '@mui/material';
 8import LoginGoogle from '../LoginGoogle';
 9import {useTranslation} from 'next-i18next';
10import {useState} from 'react';
11import {useSendMagicLinkMutation} from '../../generated/graphql';
12
13type Props = {
14  error?: string;
15  showGoogleAuth?: boolean;
16  onSend?: () => void;
17};
18
19const LoginForm = (props: Props) => {
20  const {error, showGoogleAuth, onSend} = props;
21  const {t, i18n} = useTranslation();
22  const [email, setEmail] = useState('');
23  const [sent, setSent] = useState(false);
24  const [magicLinkError, setMagicLinkError] = useState<string>(null);
25  const [sendMagicLink] = useSendMagicLinkMutation();
26
27  const handleSubmit = async () => {
28    try {
29      setMagicLinkError(null);
30      if (email) await sendMagicLink({variables: {email, lang: i18n.language}});
31      setSent(true);
32      onSend?.();
33    } catch (error) {
34      console.error(error);
35      if (error.message === 'GoogleAccount') setMagicLinkError(error.message);
36    }
37  };
38
39  return (
40    <Stack spacing={2}>
41      {(error || magicLinkError) && (
42        <FormHelperText error sx={{textAlign: 'center'}}>
43          {t(errorsMap[error || magicLinkError])}
44        </FormHelperText>
45      )}
46      {!sent && (
47        <>
48          <TextField
49            label={t`signin.email`}
50            fullWidth
51            required
52            value={email}
53            onChange={e => setEmail(e.target.value)}
54            type="email"
55          />
56          <Button
57            fullWidth
58            color="primary"
59            variant="contained"
60            disabled={!email}
61            onClick={handleSubmit}
62          >
63            {t('signin.sendLink')}
64          </Button>
65          {showGoogleAuth && (
66            <>
67              <Typography align="center">{t('signin.or')}</Typography>
68              <LoginGoogle />
69            </>
70          )}
71        </>
72      )}
73      {sent && (
74        <Typography
75          variant="body2"
76          align="center"
77          pt={2}
78        >{t`signin.check_email`}</Typography>
79      )}
80    </Stack>
81  );
82};
83
84const errorsMap = {
85  CredentialsSignin: 'signin.errors.CredentialsSignin',
86  GoogleAccount: 'signin.errors.GoogleAccount',
87};
88
89export default LoginForm;