Merge branch 'main' of https://gitea.rannes.dev/rannes.dev/wine-shop
All checks were successful
Vercel Production Deployment / Deploy-Production (push) Successful in 1m21s
All checks were successful
Vercel Production Deployment / Deploy-Production (push) Successful in 1m21s
This commit is contained in:
commit
29b09848b0
@ -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 (
|
||||
<form action={formAction}>
|
||||
<form action={formAction} className="flex flex-col gap-2">
|
||||
<Input
|
||||
name="name"
|
||||
id="name"
|
||||
className={clsx({ "border-red-500": formState.errors?.name })}
|
||||
/>
|
||||
{formState.message === "success" ? (
|
||||
<Check className="text-green-400" />
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<CircleX className="text-red-600" />
|
||||
<span>{formState.errors?.name}</span>{" "}
|
||||
</div>
|
||||
)}
|
||||
<SubmitButton text={"Country"} />
|
||||
{formState.errors?.name}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
@ -6,27 +6,32 @@ import { countries } from "../db/schema";
|
||||
import { ZodError, z } from "zod";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().min(1, { message: "Name is required" }),
|
||||
});
|
||||
|
||||
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]) {
|
||||
//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,
|
||||
|
Loading…
Reference in New Issue
Block a user