import { useState } from "react"; import { useLocation, useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; import type { components } from "../api/schema"; import { useObject, useUpdateObject, useSetFields, FieldRejection } from "../api/queries"; import { useBreadcrumb } from "../shell/use-breadcrumb"; import { ObjectForm, type ObjectCore, type ObjectFormValues } from "./object-form"; type AdminObjectView = components["schemas"]["AdminObjectView"]; export function ObjectEditForm() { const { t } = useTranslation(); const { id } = useParams(); const { data: object, isLoading } = useObject(id!); if (isLoading) return
; if (!object) return

{t("objects.notFound")}

; return ; } function ObjectEditFormLoaded({ object, id }: { object: AdminObjectView; id: string }) { const { t } = useTranslation(); const navigate = useNavigate(); const location = useLocation(); const update = useUpdateObject(); const setFields = useSetFields(); const locationState = location.state as { created?: boolean; fieldsError?: boolean; fieldErrorKey?: string; fieldErrorCode?: string; } | null; const [error, setError] = useState(() => { if (locationState?.fieldErrorKey) return t("form.fieldRejected", { field: locationState.fieldErrorKey }); if (locationState?.fieldsError) return t("form.rejected"); return null; }); const [fieldErrorKey, setFieldErrorKey] = useState( locationState?.fieldErrorKey ?? null, ); const [fieldErrorCode, setFieldErrorCode] = useState( locationState?.fieldErrorCode ?? null, ); useBreadcrumb([ { label: t("nav.objects"), to: "/objects" }, { label: object.object_number, to: `/objects/${id}` }, { label: t("actions.edit") }, ]); const core: ObjectCore = { object_number: object.object_number, object_name: object.object_name, number_of_objects: object.number_of_objects, brief_description: object.brief_description ?? null, current_location: object.current_location ?? null, current_owner: object.current_owner ?? null, recorder: object.recorder ?? null, recording_date: object.recording_date ?? null, }; const defaults = { core, fields: object.fields }; const onSubmit = async (values: ObjectFormValues): Promise => { setError(null); setFieldErrorKey(null); setFieldErrorCode(null); try { await update.mutateAsync({ id, body: values.core }); await setFields.mutateAsync({ id, fields: values.fields }); } catch (e) { if (e instanceof FieldRejection) { setFieldErrorKey(e.field); setFieldErrorCode(e.code); setError(t("form.fieldRejected", { field: e.field })); } else { setError(t("form.rejected")); } return false; } navigate(`/objects/${id}`); return true; }; return ( navigate(`/objects/${id}`)} /> ); }