snippettypescriptnextjsModeratepending
React Server Actions — Next.js form handling pattern
Viewed 0 times
Next.js 14+
Server Actionsuse serveruseFormStateuseFormStatusprogressive enhancement
nodejsbrowser
Problem
Handling form submissions in Next.js App Router requires API routes, client-side fetch, loading states, and error handling. This creates boilerplate and multiple files for simple CRUD operations.
Solution
Use React Server Actions (use server directive) for progressive enhancement. Forms work without JavaScript, and useFormState/useFormStatus provide loading and error states.
Code Snippets
Server Actions with form state and validation
// actions.ts
'use server';
import { revalidatePath } from 'next/cache';
export async function createPost(prevState: any, formData: FormData) {
const title = formData.get('title') as string;
if (!title || title.length < 3) {
return { error: 'Title must be at least 3 characters' };
}
await db.insert(posts).values({ title });
revalidatePath('/posts');
return { success: true };
}
// form.tsx
'use client';
import { useFormState, useFormStatus } from 'react-dom';
import { createPost } from './actions';
function SubmitButton() {
const { pending } = useFormStatus();
return <button disabled={pending}>{pending ? 'Saving...' : 'Create'}</button>;
}
export function PostForm() {
const [state, action] = useFormState(createPost, {});
return (
<form action={action}>
<input name="title" />
{state.error && <p className="error">{state.error}</p>}
<SubmitButton />
</form>
);
}Revisions (0)
No revisions yet.