Bachelorthesis_Code/frontend/src/components/pages/Register.js
cami 0e222d3d52
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
Autoformatting all files
2021-07-14 21:05:16 +02:00

91 lines
2.3 KiB
JavaScript

import React, { useState } from "react";
import "../../App.css";
import Footer from "../../Footer";
import InputField from "../InputField";
import SubmitField from "../SubmitField";
import "../Input.css";
import ErrorMessage from "../ErrorMessage";
import { login, useAuth } from "../../auth/AuthProvider";
import { Redirect } from "react-router-dom";
export default function Login() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const [isStatusOk, setIsStatusOk] = useState("");
const [isLoggedIn] = useAuth();
const onSubmitClick = (e) => {
e.preventDefault();
let opts = {
username: username,
password: password,
};
fetch("/api/register", {
method: "post",
body: JSON.stringify(opts),
}).then((response) => {
if (response.status === 409) {
/*
then is needed twice to get rid of the javascript Promise thing
*/
setIsStatusOk(false);
response.json().then((resp2) => {
setErrorMessage(resp2.message);
});
} else if (response.status === 200) {
response.json().then((resp) => {
fetch("/api/login", {
method: "post",
body: JSON.stringify(opts),
}).then((response) => {
response.json().then((token) => {
login(token);
});
});
});
setIsStatusOk(true);
}
});
};
const handleUsernameChange = (e) => {
setUsername(e.target.value);
};
const handlePasswordChange = (e) => {
setPassword(e.target.value);
};
return (
<>
<div className="sitePage">
<h1>Registrierung</h1>
<form>
<InputField
LabelName="Benutzername"
InputType="text"
onChange={handleUsernameChange}
InputName="username"
/>
{!isStatusOk && <ErrorMessage message={errorMessage} />}
<InputField
LabelName="Passwort"
InputType="password"
onChange={handlePasswordChange}
InputName="password"
/>
<br />
<SubmitField onClick={onSubmitClick} LabelName="Registrieren" />
</form>
{isLoggedIn && <Redirect to="/umfrage" />}
</div>
<Footer />
</>
);
}