Server Actions
~10 mins
- nextjs
Server Actions
/app/lib/actions.ts
'use server';
export async function createTask(formData: FormData) {
const rawFormData = {
taskName: formData.get('taskName'),
status: formData.get('status'),
};
// Test it out:
console.log(rawFormData);
}
/app/ui/task/create-form.tsx
import {createTask} from '@app/lib/actions';
...
<form action={createTask}>
- Good to know: In HTML, you'd pass a URL to the action attribute. This URL would be the destination where your form data should be submitted (usually an API endpoint).
However, in React, the action attribute is considered a special prop - meaning React builds on top of it to allow actions to be invoked.
Behind the scenes, Server Actions create a POST API endpoint. This is why you don't need to create API endpoints manually when using Server Actions.
- Tip: If you're working with forms that have many fields, you may want to consider using the entries() method with JavaScript's Object.fromEntries(). For example:
const rawFormData = Object.fromEntries(formData.entries());
RevalidatePath
- Once the database has been updated, the /dashboard/invoices path will be revalidated, and fresh data will be fetched from the server.
import { revalidatePath } from 'next/cache';
revalidatePath('/dashboard/invoices');
Redirect
- you also want to redirect the user back to the /dashboard/invoices page. You can do this with the redirect function from Next.js:
import { redirect } from 'next/navigation';
redirect('/dashboard/invoices');