import { useState } from "react"; import { createStudent, emptyFormValues, studentDraftSchema, toFieldErrors, type StudentField, type StudentFormErrors, type StudentFormValues, } from "../lib/students"; import StudentFields, { buttonGhostClass, buttonPrimaryClass } from "./StudentFields"; /** CREATE-only island for /add. On success it hands the user back to the list. */ export default function CreateStudentForm() { const [values, setValues] = useState(emptyFormValues); const [errors, setErrors] = useState({}); const [saving, setSaving] = useState(false); function handleChange(field: StudentField, value: string) { setValues((current) => ({ ...current, [field]: value })); // Clear the message as soon as the field is touched again. setErrors((current) => (field in current ? { ...current, [field]: undefined } : current)); } function handleSubmit(event: React.SubmitEvent) { event.preventDefault(); if (saving) return; const parsed = studentDraftSchema.safeParse(values); if (!parsed.success) { setErrors(toFieldErrors(parsed.error)); return; } setSaving(true); setErrors({}); createStudent(parsed.data); window.location.assign("/"); } return (

Add a student

Saved to local storage, then you go straight back to the list.

cancel
); }