-
Notifications
You must be signed in to change notification settings - Fork 1
/
Login.js
82 lines (73 loc) · 2.96 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const [error, setError] = useState('');
const navigate = useNavigate();
const handleSubmit = async (event) => {
event.preventDefault();
if (!username || !password) {
setError('Please fill in both username and password.');
return;
}
const url = event.target.name === 'register' ? 'my_project/register.php' : 'my_project/login.php';
try {
const response = await fetch(`http://localhost/${url}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
});
const result = await response.json();
if (result.success) {
if (event.target.name === 'login') {
navigate('/welcome'); // Redirect to welcome on successful login
}
setMessage(`${event.target.name === 'register' ? 'Registration' : 'Login'} successful!`);
setError('');
} else {
setMessage('');
setError(`${event.target.name === 'register' ? 'Registration' : 'Login'} failed: ${result.message}`);
}
} catch (error) {
console.error('Error:', error);
setMessage('');
setError('An error occurred. Please try again.');
}
};
return (
<div className="login-container">
<h2>Login / Register</h2>
<form>
<div className="form-group">
<label>Username:</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
</div>
<div className="form-group">
<label>Password:</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<div className="button-group">
<button type="button" name="login" onClick={handleSubmit}>Login</button>
<button type="button" name="register" onClick={handleSubmit}>Register</button>
</div>
</form>
{message && <p className="message">{message}</p>}
{error && <p className="error">{error}</p>}
</div>
);
}
export default Login;