({ mode, loggedin, setloggedin })
| 16 | const VITE_SERVER_PORT = import.meta.env.VITE_SERVER_PORT || "https://bitbox-uxbo.onrender.com"; |
| 17 | |
| 18 | const Login = ({ mode, loggedin, setloggedin }) => { |
| 19 | |
| 20 | const [credentials, setCredentials] = useState({ email: "", password: "" }); |
| 21 | const [loading, setLoading] = useState(false); |
| 22 | const navigate = useNavigate(); |
| 23 | const { userLoggedIn } = useAuth(); |
| 24 | |
| 25 | // Conditional navigation if user is already logged in |
| 26 | useEffect(() => { |
| 27 | if (userLoggedIn) { |
| 28 | navigate('/'); |
| 29 | } |
| 30 | }, [userLoggedIn, navigate]); |
| 31 | |
| 32 | // Handle form submission for login |
| 33 | const handleSubmit = async (e) => { |
| 34 | e.preventDefault(); |
| 35 | |
| 36 | // Check for empty fields |
| 37 | if (!credentials.email || !credentials.password) { |
| 38 | toast.error("Please enter both email and password."); |
| 39 | return; |
| 40 | } |
| 41 | |
| 42 | setLoading(true); |
| 43 | try { |
| 44 | const response = await fetch(`${VITE_SERVER_PORT}/api/auth/login`, { |
| 45 | method: "POST", |
| 46 | headers: { |
| 47 | "Content-Type": "application/json", |
| 48 | }, |
| 49 | body: JSON.stringify(credentials), |
| 50 | }); |
| 51 | |
| 52 | if (!response.ok) { |
| 53 | // Check for network or server errors |
| 54 | if (response.status === 500) { |
| 55 | toast.error("Server error. Please try again later."); |
| 56 | } else { |
| 57 | toast.error("Login failed! Please check your credentials."); |
| 58 | } |
| 59 | throw new Error("Response not ok"); |
| 60 | } |
| 61 | |
| 62 | const json = await response.json(); |
| 63 | console.log(json); |
| 64 | |
| 65 | if (json.success) { |
| 66 | localStorage.setItem("token", json.authtoken); |
| 67 | toast.success("Login Successfully!"); |
| 68 | setloggedin(!loggedin) |
| 69 | navigate("/"); |
| 70 | } else { |
| 71 | toast.error(json.message || "Login failed! Invalid credentials."); |
| 72 | } |
| 73 | } catch (error) { |
| 74 | if (error.message === "NetworkError") { |
| 75 | toast.error("Network error. Please check your connection."); |
nothing calls this directly
no test coverage detected