In Next.js 14+, you want to handle a form submission that updates user data and immediately reflects changes on the page without extra client-side fetching. Which approach is best?
Think about how Server Actions can simplify server communication and UI updates without extra client fetches.
Server Actions allow direct server-side handling of events like form submissions, enabling immediate UI updates without separate client fetches. API routes require client fetch calls and extra state management.
Consider a Server Action in Next.js that throws an error during execution. What is the expected behavior in the client component that called it?
Think about error handling responsibility in Server Actions.
Server Actions throw errors back to the client, but you must catch and handle them explicitly in your component to show user-friendly messages or fallback UI.
Which of the following code snippets correctly defines a Server Action in Next.js 14+?
export async function updateUser(data) { 'use server'; // update logic }
Server Actions require a special directive to mark them as server-only.
The 'use server' directive inside an async function marks it as a Server Action. 'use client' is for client components. Omitting 'use server' means it's not a Server Action.
You have this Next.js API route code:
export default async function handler(req, res) {
if (req.method === 'POST') {
const data = req.body;
updateDatabase(data);
res.status(200).json({ success: true });
} else {
res.status(405).end();
}
}Why might the database not update as expected?
Consider asynchronous function calls and response timing.
Not awaiting the async updateDatabase call means the response is sent before the update finishes, possibly causing incomplete updates.
Given this React Server Component with a Server Action that updates a counter:
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
async function increment() {
'use server';
setCount(count + 1);
}
return (
);
}What will the user see after clicking Increment once?
Think about React state and Server Actions interaction.
React state hooks like useState cannot be used inside Server Actions. Server Actions run on the server and cannot directly update client state. This causes an error.