import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { apiPost } from '../api';
function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const { login } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const from = location.state?.from?.pathname || '/';
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await apiPost('/api/auth/login', { username, password });
login(response.token);
navigate(from, { replace: true });
} catch (err) {
setError(err.message);
}
};
return (
<div className="container mt-4">
<h2>Login</h2>
{error && <div className="alert alert-danger">{error}</div>}
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="username" className="form-label">Username</label>
<input
type="text"
className="form-control"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
</div>
<div className="mb-3">
<label htmlFor="password" className="form-label">Password</label>
<input
type="password"
className="form-control"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<button type="submit" className="btn btn-primary">Login</button>
</form>
<p className="mt-3">
Don't have an account? <a href="/register">Register</a>
</p>
</div>
);
}
export default Login;