/** FEAT-2: Becken anlegen/bearbeiten — Name (Pflicht) + Notizen. */ import { useState, type FormEvent } from 'react' import { Link, useNavigate, useParams } from 'react-router-dom' import { de } from '../strings/de' import { createEnclosure, getEnclosure, updateEnclosure, type CreateEnclosure } from '../api/enclosures' import { useApi, useMutation } from '../hooks/useApi' interface FormState { name: string notes: string } const EMPTY: FormState = { name: '', notes: '' } /** "" -> null, sonst der Wert. */ const nn = (s: string): string | null => (s.trim() === '' ? null : s) export default function BeckenFormPage() { const t = de.pages.becken const navigate = useNavigate() const { id } = useParams() const isEdit = Boolean(id) const [form, setForm] = useState(EMPTY) const [errors, setErrors] = useState>>({}) const [initializedFor, setInitializedFor] = useState(null) const existing = useApi(() => (id ? getEnclosure(id) : Promise.resolve(null)), [id]) // Vorbefüllen im Bearbeiten-Modus (adjust-state-during-render, wie FEAT-1). if (existing.data && initializedFor !== existing.data.id) { setInitializedFor(existing.data.id) setForm({ name: existing.data.name, notes: existing.data.notes ?? '' }) } const mutation = useMutation((body: CreateEnclosure) => isEdit && id ? updateEnclosure(id, body) : createEnclosure(body), ) async function onSubmit(e: FormEvent) { e.preventDefault() if (form.name.trim() === '') { setErrors({ name: t.validation.nameRequired }) return } setErrors({}) const result = await mutation.run({ name: form.name.trim(), notes: nn(form.notes) }) if (result.ok) navigate(`/gehege/${result.value.id}`) // On failure mutation.error drives the inline alert; run() never throws. } if (isEdit && existing.loading) return

{de.common.loading}

return (

{isEdit ? t.form.editTitle : t.form.createTitle}