import { useEffect, useState } from "react"; import { useNavigate, Link } from "react-router-dom"; import toast from "react-hot-toast"; import "./Forms.css"; function LoginForm() { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); const navigate = useNavigate(); // Already logged in? skip the form and jump straight to /profile. useEffect(() => { const savedUser = localStorage.getItem("User"); if (savedUser) { navigate("/profile"); } }, [navigate]); const handleSubmit = async (event) => { event.preventDefault(); setError(""); if (!username || !password) { // TODO: Handle missing login fields. // - Compose a friendly message such as "Username and password are required." // - Save it to error state with setError(...) so it appears under the form. // - Show the same message via toast.error(...) so it's visible immediately. // - Return early so the network request below never runs. } try { const response = await fetch("/api/login", { // TODO: Complete the login request. // - HTTP method should be POST. // - Add a Content-Type header so Express knows the body is JSON. // - body: stringified JSON containing { username, password }. // (Login does NOT send email — only signup does.) }); const data = await response.json(); if (!response.ok) { // TODO: Handle failed server responses (4xx / 5xx). // - Use data.error from the server when available — it carries the // specific message your /api/login route returned (e.g. "Invalid // username or password."). // - Fall back to a generic "Login failed." if no error string came back. // - Show the message via toast.error(...) AND mirror it into the error // state with setError(...) so it appears under the form. // - Return early so the success path below does not run. } localStorage.setItem("User", JSON.stringify(data.user)); toast.success(data.message || `Welcome back, ${data.user.username}!`); navigate("/profile"); } catch (err) { console.error(err); const message = "Network error. Is the server running?"; setError(message); toast.error(message); } }; return (

Log in

{error &&

{error}

} setUsername(event.target.value)} /> setPassword(event.target.value)} />

No account? Sign up

); } export default LoginForm;