-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathLogin.js
54 lines (46 loc) · 1.92 KB
/
Login.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import React, {useState} from 'react'
import { useNavigate } from 'react-router-dom'
const Login = (props) => {
const [credentials, setCredentials] = useState({email: "", password: ""})
let navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch("http://localhost:5000/api/auth/login", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({email: credentials.email, password: credentials.password})
});
const json = await response.json()
console.log(json);
if (json.success){
// Save the auth token and redirect
localStorage.setItem('token', json.authtoken);
navigate("/");
}
else{
alert("Invalid credentials");
}
}
const onChange = (e)=>{
setCredentials({...credentials, [e.target.name]: e.target.value})
}
return (
<div>
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="email" className="form-label">Email address</label>
<input type="email" className="form-control" value={credentials.email} onChange={onChange} id="email" name="email" aria-describedby="emailHelp" />
<div id="emailHelp" className="form-text">We'll never share your email with anyone else.</div>
</div>
<div className="mb-3">
<label htmlFor="password" className="form-label">Password</label>
<input type="password" className="form-control" value={credentials.password} onChange={onChange} name="password" id="password" />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
)
}
export default Login