updated error handling and added red border on error
All checks were successful
Vercel Production Deployment / Deploy-Production (push) Successful in 1m19s

This commit is contained in:
ChrQR 2024-06-02 12:02:40 +02:00
parent ec47559cd2
commit a065e6b592
2 changed files with 43 additions and 31 deletions

View File

@ -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<HTMLFormElement>(null);
useEffect(() => {
if (formState.message === "success") {
formRef.current?.reset();
}
}, [formState.message]);
return (
<form action={formAction}>
<Input name="name" />
<Input
name="name"
id="name"
className={clsx({ "border-red-500": formState.errors?.name })}
/>
<SubmitButton text={"Country"} />
{state?.message}
{formState.errors?.name}
</form>
);
}

View File

@ -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: "",
},
};
} else {
const confirmCreate = await db
.insert(countries)
.values(newCountry.data)
.onConflictDoNothing()
.returning({ name: countries.name });
if (!confirmCreate[0]) {
} catch (error) {
const zodError = error as ZodError;
const errorMap = zodError.flatten().fieldErrors;
return {
message: `${newCountry.data.name} already exists`,
data: newCountry.data,
};
} else {
revalidatePath("/");
return {
message: `${confirmCreate[0].name} added`,
data: newCountry.data,
message: "error",
errors: {
name: errorMap["name"]?.[0] ?? "",
},
fieldValues: {
name,
},
};
}
}
}