diff --git a/src/app/_components/admin/CreateCountryForm.tsx b/src/app/_components/admin/CreateCountryForm.tsx index f7d5e21..2b72471 100644 --- a/src/app/_components/admin/CreateCountryForm.tsx +++ b/src/app/_components/admin/CreateCountryForm.tsx @@ -5,6 +5,7 @@ import SubmitButton from "../SubmitButton"; import { useFormState } from "react-dom"; import { useEffect, useRef } from "react"; import clsx from "clsx"; +import { Check, CircleX } from "lucide-react"; export default function CreateCountryForm() { const [formState, formAction] = useFormState(addCountry, { @@ -21,14 +22,21 @@ export default function CreateCountryForm() { } }, [formState.message]); return ( -
+ + {formState.message === "success" ? ( + + ) : ( +
+ + {formState.errors?.name}{" "} +
+ )} - {formState.errors?.name} ); } diff --git a/src/server/actions/addCountry.ts b/src/server/actions/addCountry.ts index 7de3b00..2bb4b66 100644 --- a/src/server/actions/addCountry.ts +++ b/src/server/actions/addCountry.ts @@ -7,29 +7,31 @@ import { ZodError, z } from "zod"; import { eq } from "drizzle-orm"; export async function addCountry(prevstate: any, formData: FormData) { - const name = formData.get("name") as string; + const name = (formData.get("name") as string).toLowerCase(); const exists = await db .select({ name: countries.name }) .from(countries) .where(eq(countries.name, name)); + //Define the schema for the form data const schema = z.object({ name: z .string() .min(1, { message: "Name is required" }) .refine(() => !exists[0], { message: `${name} already exists` }), }); + //Parse the form data using the schema for validation, and check if the name already exists try { schema.parse({ name, }); - if (!exists[0]) { - await db - .insert(countries) - .values({ name }) - .returning({ name: countries.name }); - revalidatePath("/"); - } + //If the name doesn't exist, add the country to the database abd revalidate the page + await db + .insert(countries) + .values({ name }) + .returning({ name: countries.name }); + revalidatePath("/"); + //Return a success message return { message: "success", errors: undefined,