added working create form and useActionState logic #1

Merged
christian merged 6 commits from forms into main 2024-05-25 10:26:39 +00:00
3 changed files with 55 additions and 15 deletions
Showing only changes of commit 10cdf225d9 - Show all commits

2
package-lock.json generated
View File

@ -16,7 +16,7 @@
"postgres": "^3.4.3",
"react": "18.2.0",
"react-dom": "18.2.0",
"zod": "^3.23.3"
"zod": "^3.23.8"
},
"devDependencies": {
"@types/eslint": "^8.56.2",

View File

@ -20,7 +20,7 @@
"postgres": "^3.4.3",
"react": "18.2.0",
"react-dom": "18.2.0",
"zod": "^3.23.3"
"zod": "^3.23.8"
},
"devDependencies": {
"@types/eslint": "^8.56.2",

View File

@ -1,11 +1,9 @@
'use server'
import { ZodError, z } from 'zod';
import { db } from '../db/index'
import { wines } from '../db/schema'
type Wine = {
name: string;
producer: string;
}
type NewWine = typeof wines.$inferInsert;
export type InsertResult = {
name: string;
@ -13,14 +11,56 @@ export type InsertResult = {
id: string;
createdAt: Date;
updatedAt: Date | null;
}[];
export type Fields = {
name: FormDataEntryValue | null
producer: FormDataEntryValue | null;
}
export const addWine = async (wine: Wine): Promise<InsertResult> => {
const { name, producer } = wine;
const response = await db.insert(wines).values({
producer: producer,
name: name,
})
.returning();
return response;
};
export type FormState = {
message: string;
errors: Record<keyof Fields, string> | undefined;
fieldValues: NewWine;
}
const schema = z.object({
name: z.string(),
producer: z.string().uuid(),
})
export const addWine = async (
prevState: FormState,
formData: FormData): Promise<FormState> => {
const newWine: NewWine = {
name: formData.get('name') as string,
producer: formData.get('producer') as string
}
try {
schema.parse(newWine)
const response = await db.insert(wines).values(newWine);
return {
message: `success fully added ${response}`,
errors: undefined,
fieldValues: {
name: "",
producer: ""
}
}
} catch (error) {
const zodError = error as ZodError;
const errorMap = zodError.flatten().fieldErrors;
return {
message: "error",
errors: {
name: errorMap["name"]?.[0] ?? "",
producer: errorMap["producer"]?.[0] ?? ""
},
fieldValues: {
name: newWine.name,
producer: newWine.producer
}
}
}
}