AuthContainer.js
2.72 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
93
94
95
96
97
98
99
100
101
102
import React, { useState } from "react";
import { useMutation } from "@apollo/react-hooks";
import { LOGIN, SIGNUP } from "./AuthQueries";
import useInput from "../../Hooks/useInput";
import { toast } from "react-toastify";
import AuthPresenter from "./AuthPresenter";
export default () => {
const [action, setAction] = useState("logIn");
const email = useInput("");
const password = useInput("");
const password2 = useInput("");
const phoneNum = useInput("");
const username = useInput("");
// mutations
const [login] = useMutation(LOGIN);
const [createAccount] = useMutation(SIGNUP);
// TODO: When login or signup success, get token from mutation function
let Auth;
let token;
const onSubmit = async (e) => {
e.preventDefault();
if (action === "logIn") {
if (email.value !== "") {
try {
Auth = await login({
variables: { email: email.value, password: password.value },
});
token = Auth.data.login.token;
if (!Auth) {
// when login fail
toast.warn("you need to make your own account");
setAction("signUp");
} else {
// when login success
toast.success("login success");
// TODO: move page to Main container.
}
} catch {
toast.error("login failed!");
}
} else {
toast.error("email is required!", {
position: "top-center",
autoClose: 3000,
closeOnClick: true,
draggable: true,
});
}
} else if (action === "signUp") {
if (
(email.value !== "",
username.value !== "",
password.value !== "",
password2.value !== "",
phoneNum.value !== "")
) {
try {
Auth = await createAccount({
variables: {
email: email.value,
username: username.value,
password: password.value,
password2: password2.value,
phoneNum: phoneNum.value,
},
});
token = Auth.data.createAccount.token;
if (!Auth) {
toast.warn("you need to sign up first");
setAction("signUp");
} else {
toast.success("login success");
setAction("logIn");
}
} catch {
toast.error("can't sign up, please check input data");
}
} else {
toast.error("you need to input with vaild data");
}
}
};
return (
<AuthPresenter
setAction={setAction}
action={action}
email={email}
password={password}
password2={password2}
username={username}
phoneNum={phoneNum}
onSubmit={onSubmit}
/>
);
};