"use client"; import { useEffect, useState } from "react" import { Controller, useForm } from "react-hook-form" import { InputTextR } from "../ui/inputTextR"; import { emptyLocation, Location, LocationCreate, LocationMutaion, LocationTreeNode, LocationUpdate } from "../../types/inventory"; import { locationCreate, locationTree, locationUpdate } from "../../actions/location.actions"; import { useRouter } from "next/navigation" import { sites } from "../../_config/sites"; import { LocationTreeView } from "./location.treeView"; interface Params { initData?: Location debug?: boolean } export const LocationForm = ({ initData, debug }: Params) => { const [locationTreeData, setLocationTree] = useState() useEffect(() => { const load = async () => { let d = await locationTree(); setLocationTree(d); } load(); if (initData) { const { _id, name, description, parentLocationId } = initData; setId(_id); setModeUpdate(true); reset({ name, description, parentLocationId }) } }, [initData]) const router = useRouter(); const { register, handleSubmit, formState: { errors }, watch, control, getFieldState, reset } = useForm({ defaultValues: emptyLocation }) const [modeUpdate, setModeUpdate] = useState(false); const [id, setId] = useState(); const [error, setError] = useState(); const onSubmit = async (data: LocationMutaion) => { setError(undefined); if (modeUpdate) { if (id) { locationUpdate(id, data); } else { setError('Etwas ist falsch, keine ID'); } } else { const res = await locationCreate(data); /* if (!res.ok) { setError("_id") return } */ router.push(sites.location.url) } } return (
{modeUpdate ?
Update
:
Anlegen
}
{locationTreeData && ( field.onChange(id)} /> )} /> }
{error &&
{error}
} {errors.name &&
{errors.name.message}
}
{debug &&
{watch("name")}
touched:{getFieldState("name").isTouched ? 'true' : 'false'}
{JSON.stringify(watch(), null, 2)}
}
) }