Kodeloka
  1. Kodeloka
  2. Kelas Next.js
  3. Materi

Data & Caching ยท Modul 10 dari 23

Server Actions & Form Handling ('use server')

Mengabaikan boilerplate API routes dengan Server Actions, validasi form Zod, useFormStatus, dan useActionState.

๐ŸŽฏ Poin-Poin Utama Modul Ini:
  • Server Actions didefinisikan dengan direktif 'use server' di dalam fungsi atau file terpisah
  • Dapat dipanggil langsung dari atribut action={createEvent} pada elemen HTML <form>
  • Dukungan penuh untuk Progressive Enhancement (form tetap berfungsi meski JS client belum selesai di-load)

โšก Revolusi Mutasi Data dengan Server Actions

Server Actions memungkinkan Anda menulis fungsi backend yang dapat dipanggil langsung dari komponen React client atau form tanpa perlu membuat file API route secara terpisah di app/api/.

๐Ÿ’ป Kode Contoh Server Action

app/actions.ts
"use server"; // Menandakan fungsi di file ini dieksekusi di server

import { revalidatePath } from "next/cache";

export async function createEvent(formData: FormData) {
  const title = formData.get("title") as string;
  const location = formData.get("location") as string;

  // Simpan ke database (Prisma / Supabase)
  console.log("Saving to DB:", { title, location });

  // Revalidasi cache halaman events agar UI terupdate otomatis
  revalidatePath("/events");
}