62 lines
2.1 KiB
JavaScript
62 lines
2.1 KiB
JavaScript
// src/components/Login.js
|
|
import React, { useState } from 'react';
|
|
import { Button, TextField, Container, Typography, Alert } from '@mui/material';
|
|
import axios from 'axios';
|
|
import { useNavigate } from 'react-router-dom'; // Import useNavigate
|
|
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
|
|
|
|
export default function Login({ setToken }) {
|
|
const [username, setUsername] = useState('');
|
|
const [password, setPassword] = useState('');
|
|
const [loginError, setLoginError] = useState(false); // State for login error
|
|
const navigate = useNavigate(); // Initialize useNavigate
|
|
|
|
const handleLogin = async (e) => {
|
|
e.preventDefault();
|
|
setLoginError(false); // Reset error state on each login attempt
|
|
try {
|
|
// eslint-disable-next-line no-template-curly-in-string
|
|
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/login`, { username, password });
|
|
setToken(response.data.token);
|
|
navigate('/boxes');
|
|
} catch (error) {
|
|
console.error('Login failed', error);
|
|
setLoginError(true); // Set error state if login fails
|
|
}
|
|
};
|
|
|
|
return (
|
|
<Container maxWidth="xs">
|
|
<Typography variant="h4" gutterBottom>Login</Typography>
|
|
|
|
{/* Display error message if loginError is true */}
|
|
{loginError && (
|
|
<Alert severity="error">Login Failed</Alert>
|
|
)}
|
|
|
|
<form onSubmit={handleLogin}>
|
|
<TextField
|
|
label="Username"
|
|
variant="outlined"
|
|
fullWidth
|
|
margin="normal"
|
|
value={username}
|
|
onChange={(e) => setUsername(e.target.value)}
|
|
/>
|
|
<TextField
|
|
label="Password"
|
|
type="password"
|
|
variant="outlined"
|
|
fullWidth
|
|
margin="normal"
|
|
value={password}
|
|
onChange={(e) => setPassword(e.target.value)}
|
|
/>
|
|
<Button sx={{ backgroundColor: PRIMARY_COLOR, borderBottom: '1px solid', borderColor: '#444', color: SECONDARY_COLOR }} variant="contained" color="primary" type="submit" fullWidth>
|
|
Login
|
|
</Button>
|
|
</form>
|
|
</Container>
|
|
);
|
|
}
|