yap-blog/src/lib/forms.ts
2026-07-02 21:32:33 -04:00

29 lines
847 B
TypeScript

import type { ZodError } from "zod";
/** Result shape shared by all admin form actions (via useActionState). */
export type FormState = {
status?: "success";
/** Form-level message not tied to a single field. */
formError?: string;
/** Per-field messages, keyed by input name. */
fieldErrors?: Record<string, string[]>;
};
export const initialFormState: FormState = {};
export function zodErrorToFormState(error: ZodError): FormState {
const fieldErrors: Record<string, string[]> = {};
for (const issue of error.issues) {
const key = issue.path.length > 0 ? String(issue.path[0]) : "_form";
(fieldErrors[key] ??= []).push(issue.message);
}
return { fieldErrors };
}
export function firstFieldError(
state: FormState | undefined,
field: string,
): string | undefined {
return state?.fieldErrors?.[field]?.[0];
}