import React, { useState } from "react";
import { Form, Button } from "react-bootstrap";
import axios from "axios";
import Cookies from "universal-cookie";
import "./login.css"
var cookies = new Cookies();
export default function Login() {
// initial state
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loginError, setloginError] = useState("False")
const handleSubmit = (e) => {
// prevent the form from refreshing the whole page
e.preventDefault();
// set configurations
const configuration = {
method: "post",
url: "http://localhost:3001/login",
data: {
email,
password,
},
};
// make the API call
axios(configuration)
.then((result) => {
var token_and_email = [result.data.token, email]
// set the cookie
cookies.set("TOKEN_AND_EMAIL", token_and_email, {
path: "/",
});
cookies.set("TOKEN", result.data.token, {
path: "/",
});
// set email in local storage
window.localStorage.setItem("email", email);
if (result.data.has_prev_event === false) {
window.localStorage.setItem("events", "no events");
// redirect user to event creation if they haven't made event before
window.location.href = "/event-creation";
}
else {
window.localStorage.setItem("events", JSON.stringify(result.data.events));
window.localStorage.setItem("curr_event", result.data.events[0]["event_name"]);
// redirect user to event dashboard if they have made events before
window.location.href = "/event-dashboard";
}
})
.catch((error) => {
setloginError("True");
error = new Error();
});
};
return (
<>
<div class ="split left"></div>
<div class ="split right">
<div class="centered">
<h2 class="login-title">Welcome back</h2>
<div class="login-form">
<Form onSubmit={(e) => handleSubmit(e)}>
{/* email */}
<Form.Group controlId="formBasicEmail">
<Form.Label></Form.Label>
<Form.Control
type="email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
/>
</Form.Group>
{/* password */}
<Form.Group controlId="formBasicPassword">
<Form.Label></Form.Label>
<Form.Control
type="password"
name="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
</Form.Group>
<br/>
{/* submit button */}
<Button class="loginButton"
variant="primary"
type="submit"
onClick={(e) => handleSubmit(e)}
>
Log in
</Button>
{loginError === "True" ? (
<p className="text-danger">Your credentials are incorrect, please try again</p>
) : (
<p className="text-danger"></p>
)}
</Form>
</div>
<br/>
<div class="register-link">
<a href="/register">Forgot your password?</a>
</div>
<div class="register-link">
<a href="/register">Create an account</a>
</div>
</div>
</div>
</>
);
}