aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/Login.js
blob: 717a3ae73f8e337af9e9efb424a23788617df5e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

function Login() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const navigate = useNavigate(); // Initialize useNavigate hook

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      console.log('Attempting login with:', { username, password });
      const response = await axios.post('http://localhost:5000/login', {
        username,
        password,
      });
      const { token } = response.data;
      console.log('Login successful, token:', token);
      localStorage.setItem('jwtToken', token);
      navigate('/admin'); // Redirect to the admin page
    } catch (error) {
      setError('Invalid credentials');
      console.error('Error logging in', error);
    }
  };

  return (
    <div className="Login">
      <h2>Login</h2>
      {error && <p style={{ color: 'red' }}>{error}</p>}
      <form onSubmit={handleSubmit}>
        <div>
          <label>Username:</label>
          <input
            type="text"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            required
          />
        </div>
        <div>
          <label>Password:</label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
        </div>
        <button type="submit">Login</button>
      </form>
    </div>
  );
}

export default Login;