Next. jsの Server Actions: フォーム 処理の 新しい 方法
この記事は自動翻訳されています。
記事を読み込み中...
メリークリスマス!どうぞ良いお年を。
記事を読み込み中...
この記事は自動翻訳されています。
開発者の皆さん、こんにちは!👋 Next.js 14の最もクールな機能の一つ、Server Actionsを詳しく見ていきましょう。Reactでのフォーム処理に苦労してきた方なら、これが助けになるかもしれません!
Server Actionsは、Next.jsが「複雑なAPIルートにさよなら」と言い、「よりシンプルで直感的なフォーム処理にこんにちは」と言うようなものです。サーバーへの直通回線のようなもので、仲介者は不要です!🚀
// Your form component
export default function Form() {
async function handleSubmit(formData) {
'use server'
// Handle the form submission here
const name = formData.get('name')
await saveToDatabase(name)
}
return (
<form action={handleSubmit}>
<input name="name" type="text" />
<button type="submit">Submit</button>
</form>
)
}
とてもすっきりしていますよね?ここで何が起きているのかをフローチャートで分解してみましょう:
'use server'
async function addTodo(formData) {
const todo = formData.get('todo')
try {
await db.todos.create({
data: {
content: todo,
completed: false
}
})
revalidatePath('/todos')
} catch (error) {
return { error: 'Failed to create todo' }
}
}
Server ActionsはNext.js開発者にとって画期的なものです。ワークフローが簡素化され、セキュリティが向上し、アプリのパフォーマンスも高まります。次のプロジェクトでぜひ試してみてください。将来のあなたが感謝するはずです!🎉
Server Actionsについて質問がありますか?下のコメント欄に投稿してください!楽しいコーディングを!💻