Added login failed alert

This commit is contained in:
Steve White 2024-10-08 17:26:13 -05:00
parent 4333cd5a71
commit 6671a02d65
1 changed files with 13 additions and 4 deletions

View File

@ -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"