From a065e6b5924444144cfa8a52812fa13ab6b883de Mon Sep 17 00:00:00 2001 From: ChrQR Date: Sun, 2 Jun 2024 12:02:40 +0200 Subject: [PATCH] updated error handling and added red border on error --- .../_components/admin/CreateCountryForm.tsx | 25 ++++++++-- src/server/actions/addCountry.ts | 49 +++++++++---------- 2 files changed, 43 insertions(+), 31 deletions(-) diff --git a/src/app/_components/admin/CreateCountryForm.tsx b/src/app/_components/admin/CreateCountryForm.tsx index 45ab5bf..f7d5e21 100644 --- a/src/app/_components/admin/CreateCountryForm.tsx +++ b/src/app/_components/admin/CreateCountryForm.tsx @@ -3,15 +3,32 @@ import { Input } from "~/components/ui/input"; import { addCountry } from "~/server/actions/addCountry"; import SubmitButton from "../SubmitButton"; import { useFormState } from "react-dom"; +import { useEffect, useRef } from "react"; +import clsx from "clsx"; export default function CreateCountryForm() { - const [state, formAction] = useFormState(addCountry, null); - + const [formState, formAction] = useFormState(addCountry, { + message: "", + errors: undefined, + fieldValues: { + name: "", + }, + }); + const formRef = useRef(null); + useEffect(() => { + if (formState.message === "success") { + formRef.current?.reset(); + } + }, [formState.message]); return (
- + - {state?.message} + {formState.errors?.name} ); } diff --git a/src/server/actions/addCountry.ts b/src/server/actions/addCountry.ts index 36c61fe..126bab1 100644 --- a/src/server/actions/addCountry.ts +++ b/src/server/actions/addCountry.ts @@ -3,7 +3,7 @@ import { revalidatePath } from "next/cache"; import { db } from "../db"; import { countries } from "../db/schema"; -import * as z from "zod"; +import { ZodError, z } from "zod"; const schema = z.object({ name: z.string().min(1, { message: "Name is required" }), @@ -11,33 +11,28 @@ const schema = z.object({ export async function addCountry(prevstate: any, formData: FormData) { const name = formData.get("name") as string; - const newCountry = schema.safeParse({ name: name.toLowerCase() }); - - if (!newCountry.success) { - const errors = newCountry.error.issues.map((issue) => - console.log(issue.message), - ); + try { + schema.parse({ + name, + }); return { - message: errors, - data: newCountry.data, + message: "success", + errors: undefined, + fieldValues: { + name: "", + }, + }; + } catch (error) { + const zodError = error as ZodError; + const errorMap = zodError.flatten().fieldErrors; + return { + message: "error", + errors: { + name: errorMap["name"]?.[0] ?? "", + }, + fieldValues: { + name, + }, }; - } else { - const confirmCreate = await db - .insert(countries) - .values(newCountry.data) - .onConflictDoNothing() - .returning({ name: countries.name }); - if (!confirmCreate[0]) { - return { - message: `${newCountry.data.name} already exists`, - data: newCountry.data, - }; - } else { - revalidatePath("/"); - return { - message: `${confirmCreate[0].name} added`, - data: newCountry.data, - }; - } } }