implementing useActionState
All checks were successful
Vercel Preview Deployment / Deploy-Preview (push) Successful in 2m6s

This commit is contained in:
christian 2024-05-25 07:29:02 +02:00
parent 299df4569e
commit f76e72db80
2 changed files with 24 additions and 14 deletions

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"; import { getProducers } from "~/server/actions/allProducers";
type Wine = { type Wine = {
@ -6,21 +7,21 @@ type Wine = {
producer: string; 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(); const producers = await getProducers();
export default function CreateWine() { export default function CreateWine() {
const [formState, formAction] = useActionState(addWine, {
message: "",
errors: undefined,
fieldValues: {
name: "",
producer: "",
},
});
return ( return (
<div> <div>
<form action={submitWine}> <form action={formAction}>
<input type="text" name="name" /> <input type="text" name="name" />
<select name="producer"> <select name="producer">
{producers.map((producer, i) => ( {producers.map((producer, i) => (

View File

@ -2,16 +2,25 @@
import { db } from '../db/index' import { db } from '../db/index'
import { wines } from '../db/schema' import { wines } from '../db/schema'
type wine = { type Wine = {
name: string; name: string;
producer: 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; const { name, producer } = wine;
await db.insert(wines).values({ const response = await db.insert(wines).values({
producer: producer, producer: producer,
name: name, name: name,
}) })
.returning(); .returning();
return response;
}; };