mentorenwahl/docker/frontend/pages/login.tsx

64 lines
1.6 KiB
TypeScript
Raw Normal View History

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 14:38:36 +00:00
const LOGIN = gql`
mutation Login($email: String!, $password: String!) {
login(email: $email, password: $password) {
token
}
}
`;
function Login(): JSX.Element {
const [login, { error }] = useMutation(LOGIN);
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;
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;