Added login failed alert
This commit is contained in:
parent
4333cd5a71
commit
6671a02d65
|
@ -1,29 +1,38 @@
|
|||
// src/components/Login.js
|
||||
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 { useNavigate } from 'react-router-dom'; // Import useNavigate
|
||||
|
||||
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}/login`, { username, password });
|
||||
setToken(response.data.token); // Store the token in state or context
|
||||
navigate('/boxes'); //redirect to /boxes after successful login
|
||||
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"
|
||||
|
|
Loading…
Reference in New Issue