feat: 使用server action实现创建代码片段功能

This commit is contained in:
ngc2207 2024-11-11 11:27:19 +08:00
parent a910325462
commit 6978d3483b

View File

@ -1,6 +1,26 @@
import { db } from "@/db";
import { redirect } from "next/navigation";
export default function SnippetCreatePage() { 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("/");
}
return ( return (
<form> <form action={createSnippet}>
<h3 className="font-bold m-3">Create a Snippet</h3> <h3 className="font-bold m-3">Create a Snippet</h3>
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div className="flex gap-4"> <div className="flex gap-4">