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