2022-02-02 14:38:36 +00:00
|
|
|
import type { FormEvent, FormEventHandler } from "react";
|
|
|
|
import { gql, useMutation } from "@apollo/client";
|
|
|
|
import Cookies from "js-cookie";
|
|
|
|
import Router from "next/router";
|
2022-01-29 15:40:39 +00:00
|
|
|
|
2022-02-02 14:38:36 +00:00
|
|
|
import * as cookieNames from "../lib/cookieNames";
|
2022-01-29 15:40:39 +00:00
|
|
|
|
2022-02-02 20:54:14 +00:00
|
|
|
const LOGIN_MUTATION = gql`
|
2022-02-02 14:38:36 +00:00
|
|
|
mutation Login($email: String!, $password: String!) {
|
|
|
|
login(email: $email, password: $password) {
|
|
|
|
token
|
|
|
|
}
|
|
|
|
}
|
|
|
|
`;
|
|
|
|
|
|
|
|
function Login(): JSX.Element {
|
2022-02-02 20:54:14 +00:00
|
|
|
const [login, { error }] = useMutation(LOGIN_MUTATION);
|
2022-02-02 14:38:36 +00:00
|
|
|
|
|
|
|
const loginUser: FormEventHandler = async (
|
|
|
|
event: FormEvent & { target: HTMLFormElement }
|
|
|
|
): Promise<void> => {
|
2022-01-29 15:40:39 +00:00
|
|
|
event.preventDefault();
|
|
|
|
|
|
|
|
const input = {
|
2022-02-02 14:38:36 +00:00
|
|
|
email: event.target.email.value as string,
|
|
|
|
password: event.target.password.value as string,
|
2022-01-29 15:40:39 +00:00
|
|
|
};
|
2022-02-02 14:38:36 +00:00
|
|
|
const data = (
|
|
|
|
await login({
|
|
|
|
variables: { email: input.email, password: input.password },
|
|
|
|
})
|
|
|
|
).data;
|
2022-02-02 20:54:14 +00:00
|
|
|
|
2022-02-02 14:38:36 +00:00
|
|
|
if (data) {
|
|
|
|
Cookies.set(cookieNames.TOKEN, data.login.token, { expires: 1 });
|
|
|
|
Router.push("/");
|
|
|
|
}
|
|
|
|
};
|
2022-01-29 15:40:39 +00:00
|
|
|
|
|
|
|
return (
|
|
|
|
<div>
|
|
|
|
<h1>Login:</h1>
|
|
|
|
<form onSubmit={loginUser}>
|
|
|
|
<label htmlFor="email">Email:</label>
|
|
|
|
<br />
|
|
|
|
<input type="email" id="email" autoComplete="email" required />
|
|
|
|
<br />
|
|
|
|
<label htmlFor="password">Password:</label>
|
|
|
|
<br />
|
|
|
|
<input
|
|
|
|
type="password"
|
|
|
|
id="password"
|
|
|
|
autoComplete="current-password"
|
|
|
|
required
|
|
|
|
/>
|
|
|
|
<br />
|
|
|
|
<button type="submit">Login</button>
|
|
|
|
</form>
|
2022-02-02 14:38:36 +00:00
|
|
|
{error && <p style={{ color: "red" }}>{error.message}</p>}
|
2022-01-29 15:40:39 +00:00
|
|
|
</div>
|
|
|
|
);
|
2022-02-02 14:38:36 +00:00
|
|
|
}
|
2022-01-29 15:40:39 +00:00
|
|
|
|
|
|
|
export default Login;
|