From a817f718d58583fdbcecc0529cb318a2987c245f Mon Sep 17 00:00:00 2001 From: ngc2207 Date: Tue, 12 Nov 2024 17:06:10 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E5=88=9B=E5=BB=BA?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E7=89=87=E6=AE=B5=E7=95=8C=E9=9D=A2=E5=86=85?= =?UTF-8?q?=E5=AE=B9=E9=AA=8C=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/actions/index.ts | 29 ++++++++++++++++++++++++++++ src/app/snippets/new/page.tsx | 36 ++++++++++++++++------------------- 2 files changed, 45 insertions(+), 20 deletions(-) diff --git a/src/actions/index.ts b/src/actions/index.ts index 5ceaf02..985c956 100644 --- a/src/actions/index.ts +++ b/src/actions/index.ts @@ -17,3 +17,32 @@ export async function deleteSnippet(id: number) { redirect("/"); } + +export async function createSnippet( + formState: { message: string }, + formData: FormData +) { + // Check the user's inputs and make sure they're valid + const title = formData.get("title"); + const code = formData.get("code"); + if (typeof title !== "string" || title.length < 3) { + return { + message: "Title must be longer", + }; + } + if (typeof code !== "string" || code.length < 10) { + return { + message: "Code must be longer", + }; + } + // Create a new record in the database + const snippet = await db.snippet.create({ + data: { + title: title, + code: code, + }, + }); + console.log(snippet); + // Redirect the user back to the root route + redirect("/"); +} diff --git a/src/app/snippets/new/page.tsx b/src/app/snippets/new/page.tsx index 2659bb2..0595ad0 100644 --- a/src/app/snippets/new/page.tsx +++ b/src/app/snippets/new/page.tsx @@ -1,26 +1,15 @@ -import { db } from "@/db"; -import { redirect } from "next/navigation"; +"use client"; + +import * as actions from "@/actions"; +import { useActionState } from "react"; export default function SnippetCreatePage() { - async function createSnippet(formData: FormData) { - // This needs to be a server action! - "use server"; - // Check the user's inputs and make sure they're valid - const title = formData.get("title") as string; - const code = formData.get("code") as string; - // Create a new record in the database - const snippet = await db.snippet.create({ - data: { - title: title, - code: code, - }, - }); - console.log(snippet); - // Redirect the user back to the root route - redirect("/"); - } + const [formState, action] = useActionState(actions.createSnippet, { + message: "", + }); + return ( -
+

Create a Snippet

@@ -39,6 +28,13 @@ export default function SnippetCreatePage() {
+ + {formState.message ? ( +
+ {formState.message} +
+ ) : null} +