import { useState } from "react"; import { useNavigate, Link } from "react-router-dom"; import toast from "react-hot-toast"; import "./Forms.css"; function SignupForm() { const [username, setUsername] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); const navigate = useNavigate(); const validateInputs = () => { // TODO: Validate username, email, and password. // - Username must be at least 3 characters (after trimming whitespace). // - Email must look like text@text.text — a regex such as // /^[^\s@]+@[^\s@]+\.[^\s@]+$/ is enough for this assignment. // - Password must be at least 8 characters. // // Return a human-readable error string when something is invalid. // Return an empty string ("") when everything passes. // // Check fields in order (username, then email, then password) and // return after the first failure so the user only sees one error // at a time. }; const handleSubmit = async (event) => { event.preventDefault(); setError(""); const validationError = validateInputs(); if (validationError) { setError(validationError); toast.error(validationError); return; } try { const response = await fetch("/api/register", { // TODO: Complete the register request. // - HTTP method should be POST. // - Add a Content-Type header so Express knows the body is JSON. // - body: stringified JSON containing { username, email, password }. // // Hint: this is the same fetch shape we used in Lesson 15. The // Vite dev-server proxy forwards "/api/..." to your Express server // on port 3000. }); const data = await response.json(); if (!response.ok) { const message = data.error || "Signup failed."; setError(message); toast.error(message); return; } localStorage.setItem("User", JSON.stringify(data.user)); toast.success(data.message || "Signup successful."); navigate("/profile"); } catch (err) { // TODO: Handle network errors. // - This block runs when the request never reaches the server // (server down, Wi-Fi off, wrong port, proxy not restarted, etc.). // - Log the real error object with console.error so you can debug it. // - Show a toast.error so the user knows what happened. // - Mirror the same message into the error state via setError so // it shows under the form too. // - Keep the message helpful but generic — something like // "Network error. Is the server running?" works well. } }; return (
); } export default SignupForm;