NextJS:ServerActions
lastmod 2023-12-16created 2023-08-1910 edits
A new solution proposed by Next for form state management, caching, and validation.
You can change server data with form data, and run functions that execute on the server directly from the client without an intermediate API layer.
Features
- Revalidate cached data with revalidatePath() or revalidateTag()
- Navigate to another route with redirect()
- Set & read cookies with cookies()
- Handle optimistic UI with useOptimistic()
- Handle errors raised on the server with useFormState()
- Show loading state with useFormStatus()
How use it
Using the form's action
import db from './db'
import { redirect } from 'next/navigation'
async function create(formData: FormData){
'use serevr'
const post = await db.post.insert({
title: formData.get('title'),
content: formData.get('content'),
})
redirect(`/blog/${post.slug}`)
}
export default function Page(){
return (
<form action={create}>
<input type="text" name="title" />
<textarea name="content" />
<button type="submit">Submit</button>
</form>
)
}
Using formAction
export default function Page() {
async function handleSubmit() {
'use server';
// ...
}
async function submitImage() {
'use server';
// ...
}
return (
<form action={handleSubmit}>
<input type="text" name="name" />
<input type="image" formAction={submitImage} />
<button type="submit">Submit</button>
</form>
);
}
Using React's startTransition
How to call a server action from a client component
app/actions.js file:
'use server'; // client-component 파일에서 server action 직접 정의할 수 없기 때문에, 따로 파일을 만들어야합니다.
export async function addItem(id) {
await addItemToDb(id);
revalidatePath(`/product/${id}`);
}
app/components/example-client-component.js file:
'use client';
import { useTransition } from 'react';
import { addItem } from '../actions';
function ExampleClientComponent({ id }) {
let [isPending, startTransition] = useTransition();
return (
<button onClick={() => startTransition(() => addItem(id))}>
Add To Cart
</button>
);
}
Fetching Data on the Server with fetch
useFormStatus
APIs
revalidatePath
revalidateTag
See also
Favorite site
- (nextjs) Server Action
- About Next.js 13.4 Server Actions ("use server")
- The Server actions feature of Next.js - Coding Apple online course
- Exploring Next.js Server Actions | Yujiseok
Documentation
- Functions: Server Actions | Next.js
- Data Fetching: Fetching, Caching, and Revalidating | Next.js
- Data Fetching: Server Actions | Next.js
- Data Fetching: Forms and Mutations | Next.js
Pages that link here