Server Actions
Check this guide (opens in a new tab) to learn more about server actions and mutations.
-
Create a Next.js application then install and setup Prisma.
-
Create a schema for managing a collection of records. A record has an automatically-generated
id
entifier and a requiredtitle
:prisma/schema.prismagenerator client { provider = "prisma-client-js" } datasource db { provider = "sqlite" url = env("DATABASE_URL") } model Record { id String @id @default(cuid(2)) title String }
-
Create a CRUD data repository service to manage records:
repos/records.jsimport prisma from "@/repos/prisma"; export async function read(id) { if (id) { return await prisma.record.findMany({ where: { id } }); } return await prisma.record.findMany(); } export async function create(data) { return await prisma.record.create({ data }); }
-
Create a page that allows a user to manage their ideas, using server actions to retrieve, create, and delete records. Do not store the records using web storage!
app/actions.js"use server"; import { revalidatePath } from "next/cache"; import * as records from "@/repos/records"; export async function get(id) { return await records.read(id); } export async function add(data) { const record = await records.create(data); revalidatePath(`/`); return record; }