"use client" import { useState } from "react" import { zodResolver } from "@hookform/resolvers/zod" import { useForm } from "react-hook-form" import * as z from "zod" import { Button } from "@/components/ui/button" import { Field, FieldError, FieldGroup, FieldLabel, } from "@/components/ui/field" import { Input } from "@/components/ui/input" const schema = z.object({ name: z.string().min(1, { message: "Name is required." }), code: z.string().min(1, { message: "Phone number is required." }), }) type FormValues = z.infer export interface Customer { id: string name: string code: string } export function CustomerForm({ customerEdit, setEditOpen, refetchItems, }: { customerEdit: Customer | null setEditOpen: React.Dispatch> refetchItems: () => void }) { const isEditing = customerEdit !== null const [serverError, setServerError] = useState(null) const { register, handleSubmit, formState: { errors, isSubmitting }, } = useForm({ resolver: zodResolver(schema), }) async function onSubmit(values: FormValues) { setServerError(null) const res = await fetch( `/api/customers${isEditing ? `/${customerEdit.id}` : ""}`, { method: isEditing ? "PATCH" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values), } ) if (!res.ok) { const data = await res.json() setServerError(data.error || "An error occurred.") return } setEditOpen(false) refetchItems() } return (
Name Code {serverError && (

{serverError}

)}
) }