Added login failed alert
This commit is contained in:
parent
4333cd5a71
commit
6671a02d65
|
@ -1,29 +1,38 @@
|
||||||
// src/components/Login.js
|
// src/components/Login.js
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { Button, TextField, Container, Typography } from '@mui/material';
|
import { Button, TextField, Container, Typography, Alert } from '@mui/material';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { useNavigate } from 'react-router-dom'; // Import useNavigate
|
import { useNavigate } from 'react-router-dom'; // Import useNavigate
|
||||||
|
|
||||||
export default function Login({ setToken }) {
|
export default function Login({ setToken }) {
|
||||||
const [username, setUsername] = useState('');
|
const [username, setUsername] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
|
const [loginError, setLoginError] = useState(false); // State for login error
|
||||||
const navigate = useNavigate(); // Initialize useNavigate
|
const navigate = useNavigate(); // Initialize useNavigate
|
||||||
|
|
||||||
const handleLogin = async (e) => {
|
const handleLogin = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
setLoginError(false); // Reset error state on each login attempt
|
||||||
try {
|
try {
|
||||||
// eslint-disable-next-line no-template-curly-in-string
|
// eslint-disable-next-line no-template-curly-in-string
|
||||||
|
|
||||||
const response = await axios.post(`${process.env.REACT_APP_API_URL}/login`, { username, password });
|
const response = await axios.post(`${process.env.REACT_APP_API_URL}/login`, { username, password });
|
||||||
setToken(response.data.token); // Store the token in state or context
|
setToken(response.data.token);
|
||||||
navigate('/boxes'); //redirect to /boxes after successful login
|
navigate('/boxes');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Login failed', error);
|
console.error('Login failed', error);
|
||||||
|
setLoginError(true); // Set error state if login fails
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container maxWidth="xs">
|
<Container maxWidth="xs">
|
||||||
<Typography variant="h4" gutterBottom>Login</Typography>
|
<Typography variant="h4" gutterBottom>Login</Typography>
|
||||||
|
|
||||||
|
{/* Display error message if loginError is true */}
|
||||||
|
{loginError && (
|
||||||
|
<Alert severity="error">Login Failed</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
<form onSubmit={handleLogin}>
|
<form onSubmit={handleLogin}>
|
||||||
<TextField
|
<TextField
|
||||||
label="Username"
|
label="Username"
|
||||||
|
|
Loading…
Reference in New Issue