Locaft-backend/src/components/SignIn.js

61 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-11-09 08:45:04 -08:00
2020-11-29 09:05:56 -08:00
import React, { useState, useContext } from "react";
import { useHistory } from "react-router-dom";
import UserContext from "../context/UserContext";
import Axios from "axios";
import { Link } from "react-router-dom";
import ErrorNotice from "./ErrorNotice";
2020-11-09 08:45:04 -08:00
2020-11-29 09:05:56 -08:00
const SignInForm = () => {
2020-11-25 08:04:55 -08:00
2020-11-29 09:05:56 -08:00
const [email, setEmail] = useState();
const [password, setPassword] = useState();
const [error, setError] = useState();
const { setUserData } = useContext(UserContext);
const history = useHistory();
2020-11-09 08:45:04 -08:00
2020-11-29 09:05:56 -08:00
const submit = async (e) => {
e.preventDefault();
try {
const loginUser = { email, password };
const loginRes = await Axios.post(
"http://localhost:5000/users/login",
loginUser
);
setUserData({
token: loginRes.data.token,
user: loginRes.data.user,
});
localStorage.setItem("auth-token", loginRes.data.token);
history.push("/");
} catch (err) {
err.response.data.msg && setError(err.response.data.msg);
}
};
2020-11-09 08:45:04 -08:00
return (
2020-11-28 09:28:50 -08:00
2020-11-09 08:45:04 -08:00
<div className="FormCenter">
2020-11-29 09:05:56 -08:00
<form className="FormFields" onSubmit={submit}>
2020-11-09 08:45:04 -08:00
<div className="FormField">
<label className="FormField__Label" htmlFor="email">E-Mail Address</label>
2020-11-29 09:05:56 -08:00
<input type="email" id="email" className="FormField__Input" value={ email } placeholder="Enter your email" name="email" onChange={(e) => setEmail(e.target.value)} />
2020-11-09 08:45:04 -08:00
</div>
<div className="FormField">
<label className="FormField__Label" htmlFor="password">Password</label>
2020-11-29 09:05:56 -08:00
<input type="password" id="password" className="FormField__Input" value={ password } placeholder="Enter your password" name="password" onChange={(e) => setPassword(e.target.value)} />
2020-11-09 08:45:04 -08:00
</div>
<div className="FormField">
2020-11-29 09:05:56 -08:00
<button className="FormField__Button mr-20" >Sign In</button> <Link exact to="/sign-up" className="FormField__Link">Not a member?</Link>
2020-11-09 08:45:04 -08:00
</div>
</form>
2020-11-29 09:05:56 -08:00
{error && (
<ErrorNotice message={error} clearError={() => setError(undefined)} />
)}
2020-11-09 08:45:04 -08:00
</div>
);
}
export default SignInForm;