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 ( -