Login.js
2.15 KB
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
85
86
87
88
89
90
91
92
import React, { useState, useContext } from "react";
import { Form, Button } from "semantic-ui-react";
import gql from "graphql-tag";
import { useMutation } from "@apollo/react-hooks";
import { useForm } from "../utils/hook";
import { AuthContext } from "../context/auth";
const Login = props => {
const context = useContext(AuthContext);
const [errors, setErrors] = useState({});
const { onChange, onSubmit, values } = useForm(loginUser, {
username: "",
password: ""
});
const [addUser, { loading }] = useMutation(LOGIN_USER, {
update(
_,
{
data: { login: userData }
}
) {
console.log(userData);
context.login(userData);
props.history.push("/");
},
onError(err) {
setErrors(err.graphQLErrors[0].extensions.exception.errors);
},
variables: values
});
function loginUser() {
addUser();
}
return (
<div className="form-container">
<Form onSubmit={onSubmit} noValidate className={loading ? "loading" : ""}>
<h1>Login</h1>
<Form.Input
label="Username"
placeholder="Username..."
name="username"
type="text"
error={errors.username ? true : false}
value={values.username}
onChange={onChange}
></Form.Input>
<Form.Input
label="Password"
placeholder="Password..."
name="password"
type="password"
error={errors.password ? true : false}
value={values.password}
onChange={onChange}
></Form.Input>
<Button type="submit" primary>
Login
</Button>
</Form>
{Object.keys(errors).length > 0 && (
<div className="ui error message">
<ul className="list">
{Object.values(errors).map(value => (
<li key={value}>{value} </li>
))}
</ul>
</div>
)}
</div>
);
};
const LOGIN_USER = gql`
mutation login($username: String!, $password: String!) {
login(username: $username, password: $password) {
id
email
username
createdAt
token
}
}
`;
export default Login;