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
2 changed files with 24 additions and 14 deletions
Showing only changes of commit f76e72db80 - Show all commits

View File

@ -1,4 +1,5 @@
import { addWine } from "~/server/actions/addWine";
import { useActionState } from "react";
import { InsertResult, addWine } from "~/server/actions/addWine";
import { getProducers } from "~/server/actions/allProducers";
type Wine = {
@ -6,21 +7,21 @@ type Wine = {
producer: string;
};
async function submitWine(formData: FormData): Promise<void> {
"use server";
const wine: Wine = {
name: formData.get("name") as string,
producer: formData.get("producer") as string,
};
addWine(wine);
}
const producers = await getProducers();
export default function CreateWine() {
const [formState, formAction] = useActionState(addWine, {
message: "",
errors: undefined,
fieldValues: {
name: "",
producer: "",
},
});
return (
<div>
<form action={submitWine}>
<form action={formAction}>
<input type="text" name="name" />
<select name="producer">
{producers.map((producer, i) => (

View File

@ -2,16 +2,25 @@
import { db } from '../db/index'
import { wines } from '../db/schema'
type wine = {
type Wine = {
name: string;
producer: string;
}
export const addWine = async (wine: wine) => {
export type InsertResult = {
name: string;
producer: string;
id: string;
createdAt: Date;
updatedAt: Date | null;
}[];
export const addWine = async (wine: Wine): Promise<InsertResult> => {
const { name, producer } = wine;
await db.insert(wines).values({
const response = await db.insert(wines).values({
producer: producer,
name: name,
})
.returning();
return response;
};