In traditional React apps, handling a form meant creating a separate REST endpoint, writing a fetch() call, managing loading booleans, and parsing JSON errors manually. In the Next.js App Router, Server Actions let your form call an async server function directly—with React's useActionState hook handling loading and validation messages automatically. In this tutorial, you will build a student course feedback form without writing a custom API route.
<form action={formAction}> → useActionState (isPending) → 'use server' Action → Updated State & Errors
1. Create the Server Action (app/actions.ts)
A Server Action starts with the 'use server' directive. When connected to useActionState, it receives the previous state first and the browser's FormData second:
'use server';
export type FeedbackState = {
success: boolean;
message: string;
errors?: {
comment?: string;
};
};
export async function submitFeedback(
_prevState: FeedbackState,
formData: FormData
): Promise<FeedbackState> {
const course = String(formData.get('course') ?? '').trim();
const comment = String(formData.get('comment') ?? '').trim();
if (comment.length < 10) {
return {
success: false,
message: 'Please fix the form errors below.',
errors: { comment: 'Feedback must be at least 10 characters long.' },
};
}
// Save to database or log on the server
console.log('Saved feedback for:', course, comment);
return {
success: true,
message: `Thanks! Your feedback for ${course || 'this course'} was saved.`,
};
}
2. Build the Client Form with useActionState (app/feedback-form.tsx)
Because hooks run in the browser, mark the form component with 'use client' and connect submitFeedback via useActionState:
'use client';
import { useActionState } from 'react';
import { submitFeedback, type FeedbackState } from './actions';
const initialState: FeedbackState = {
success: false,
message: '',
};
export default function FeedbackForm() {
const [state, formAction, isPending] = useActionState(
submitFeedback,
initialState
);
return (
<form action={formAction}>
<label htmlFor="course">Course Name</label>
<input id="course" name="course" defaultValue="ASP.NET Core" required />
<label htmlFor="comment">Your Feedback</label>
<textarea id="comment" name="comment" rows={3} required />
{state.errors?.comment && <p>{state.errors.comment}</p>}
<button type="submit" disabled={isPending}>
{isPending ? 'Saving...' : 'Submit Feedback'}
</button>
{state.message && <p>{state.message}</p>}
</form>
);
}
3. Render the Form in app/page.tsx
import FeedbackForm from './feedback-form';
export default function HomePage() {
return (
<main>
<h1>Student Course Feedback</h1>
<FeedbackForm />
</main>
);
}
Understand the Key Ideas
'use server'ensuressubmitFeedbackruns strictly on the server—safe for database writes and secrets.useActionStatereturns[state, formAction, isPending], replacing separateuseStateflags for loading and errors.- Each input's
nameattribute (course,comment) maps directly toformData.get(...)on the server.
Practice
- Add a numeric
ratingfield (1 to 5) and validate on the server that the score is between 1 and 5. - Call
revalidatePath('/')inside your Server Action after saving to a list so the page refreshes automatically. - Display a styled green banner when
state.successistrueand a red alert whenfalse.
Continue learning: React.js Tutorials and Examples.
References: Next.js Documentation; React useActionState Reference.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.