blob: 6c90e67c8021bc3a5ef3b5b1609b58ee972ba0fe (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { Button, Fieldset, Input } from "../../components/forms";
import { login } from "../../store/auth/auth.slice";
function LoginForm() {
const [inputEmailValue, setInputEmailValue] = useState("");
const [inputPasswordValue, setInputPasswordValue] = useState("");
const [errorMsg, setErrorMsg] = useState("");
const usersList = useSelector((state) => state.users);
const dispatch = useDispatch();
const navigate = useNavigate();
const getCurrentUser = (email) => {
return usersList.find((user) => user.email === email);
};
const isValidUser = (email) => {
const currentUser = getCurrentUser(email);
return currentUser ? true : false;
};
const isValidPassword = (currentUser, password) => {
return currentUser.password === password;
};
const handleSubmit = (e) => {
e.preventDefault();
if (isValidUser(inputEmailValue)) {
const currentUser = getCurrentUser(inputEmailValue);
if (isValidPassword(currentUser, inputPasswordValue)) {
setErrorMsg("");
dispatch(login(currentUser));
navigate("/");
} else {
setErrorMsg("The password does not match.");
}
} else {
setErrorMsg("This email address does not exist.");
}
};
const displayError = (msg) => {
return msg ? <p>{msg}</p> : "";
};
return (
<form
action="#"
method="post"
className="form form--login"
onSubmit={handleSubmit}
>
{displayError(errorMsg)}
<Fieldset legend="Sign In">
<Input
label="Email"
id="login-email"
name="login-email"
value={inputEmailValue}
updateValue={setInputEmailValue}
type="email"
required
/>
<Input
label="Password"
id="login-password"
name="login-password"
value={inputPasswordValue}
updateValue={setInputPasswordValue}
type="password"
required
/>
<Button type="submit" modifiers={["submit"]}>
Log in
</Button>
</Fieldset>
</form>
);
}
export default LoginForm;
|