app/src/containers/SignIn/SignIn.js (view raw)
1import React, {useCallback, useState, useMemo} from 'react';
2import {Redirect} from 'react-router-dom';
3import {useTranslation} from 'react-i18next';
4import {useAuth} from 'strapi-react-context';
5import TextField from '@material-ui/core/TextField';
6import Button from '@material-ui/core/Button';
7import CardContent from '@material-ui/core/CardContent';
8import {CircularProgress} from '@material-ui/core';
9import CardActions from '@material-ui/core/CardActions';
10import {useToast} from '../../contexts/Toast';
11
12export default () => {
13 const {t} = useTranslation();
14 const {login, token, authState} = useAuth();
15 const [isLoading, setIsLoading] = useState(false);
16 const [email, setEmail] = useState('');
17 const [password, setPassword] = useState('');
18 const {addToast} = useToast();
19
20 const canSubmit = useMemo(
21 () => [email, password].filter(s => s.length < 4).length === 0,
22 [email, password]
23 );
24
25 const onSubmit = useCallback(
26 async evt => {
27 if (evt.preventDefault) evt.preventDefault();
28 if (isLoading) {
29 return;
30 }
31 setIsLoading(true);
32 try {
33 const error = await login(email, password);
34 if (error) {
35 addToast(t('signin.errors'));
36 }
37
38 // TODO add to my event if saved in local storage
39 // TODO remove from local storage.
40 } catch (error) {
41 console.log('ERROR', {error});
42 }
43
44 setIsLoading(false);
45 return false;
46 },
47 [email, password, login, isLoading, addToast, t]
48 );
49
50 if (token) {
51 return <Redirect to="/dashboard" />;
52 }
53 if (authState && authState.user && !authState.user.confirmed) {
54 return <Redirect to="/confirm" />;
55 }
56 return (
57 <form onSubmit={onSubmit}>
58 <CardContent>
59 <TextField
60 label={t('signin.email')}
61 fullWidth
62 required={true}
63 margin="dense"
64 value={email}
65 onChange={({target: {value = ''}}) => setEmail(value)}
66 id="SignInEmail"
67 name="email"
68 type="email"
69 />
70 <TextField
71 label={t('signin.password')}
72 fullWidth
73 required={true}
74 margin="dense"
75 value={password}
76 onChange={({target: {value = ''}}) => setPassword(value)}
77 id="SignInEmail"
78 name="password"
79 type="password"
80 />
81 </CardContent>
82 <CardActions>
83 <Button
84 color="primary"
85 variant="contained"
86 type="submit"
87 disabled={!canSubmit}
88 aria-disabled={!canSubmit}
89 id="SignInSubmit"
90 >
91 {t('signin.login')}
92 {isLoading && <CircularProgress size={20} />}
93 </Button>
94 <Button id="SignInRegister" href="/register">
95 {t('signin.register')}
96 </Button>
97 </CardActions>
98 </form>
99 );
100};