5 min read
ā¢Question 19 of 47mediumWhat are Server Actions in Next.js?
Mutating data with Server Actions.
What You'll Learn
- Creating Server Actions
- Form handling
- Optimistic updates
Basic Server Action
code.txtTSX
// app/actions.ts
'use server';
export async function createPost(formData: FormData) {
const title = formData.get('title');
const content = formData.get('content');
await db.post.create({
data: { title, content }
});
revalidatePath('/posts');
}With Forms
code.txtTSX
import { createPost } from './actions';
export default function NewPost() {
return (
<form action={createPost}>
<input name="title" placeholder="Title" />
<textarea name="content" placeholder="Content" />
<button type="submit">Create</button>
</form>
);
}With useFormState
code.txtTSX
'use client';
import { useFormState } from 'react-dom';
import { createPost } from './actions';
const initialState = { message: '', errors: {} };
export default function Form() {
const [state, formAction] = useFormState(createPost, initialState);
return (
<form action={formAction}>
<input name="title" />
{state.errors?.title && <p>{state.errors.title}</p>}
<button>Submit</button>
{state.message && <p>{state.message}</p>}
</form>
);
}Pending State
code.txtTSX
'use client';
import { useFormStatus } from 'react-dom';
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button disabled={pending}>
{pending ? 'Submitting...' : 'Submit'}
</button>
);
}