Consider a Next.js server action that updates a database record and then triggers a UI refresh. What is the main benefit of using server actions for this mutation?
export async function updateUserName(userId, newName) { await db.user.update({ where: { id: userId }, data: { name: newName } }); revalidatePath('/profile'); }
Think about how server actions run on the server and how Next.js handles UI updates.
Server actions run on the server and can directly update data sources. After mutation, Next.js can revalidate and refresh the UI automatically, avoiding complex client state management.
Identify the correct syntax to define a server action that deletes a post by ID in Next.js.
Server actions must be async functions exported from the module.
Server actions are async functions exported from the file. Option D correctly uses export async function. Option D misses async, C is not exported, D has invalid syntax.
Given this server action, why does the UI not reflect the updated data after calling it?
export async function addComment(postId, comment) { await db.comment.create({ data: { postId, text: comment } }); // Missing revalidatePath }
Think about how Next.js knows to refresh the UI after data changes.
Server actions must trigger UI refresh explicitly by calling revalidatePath or similar. Without it, the UI shows stale data.
Why do server actions in Next.js improve security when performing mutations compared to client-side mutations?
Consider where the code runs and what the client can see.
Server actions run only on the server, so secrets like database credentials and validation logic are never exposed to the client, improving security.
Given this server action that updates a user's email and triggers revalidation, what will the UI show immediately after the action completes?
export async function updateEmail(userId, newEmail) { await db.user.update({ where: { id: userId }, data: { email: newEmail } }); await revalidatePath('/profile'); } // Assume the profile page fetches user data server-side and displays the email.
Think about how Next.js handles revalidation and server data fetching.
Calling revalidatePath triggers Next.js to refresh the server-rendered data for the path, so the UI updates automatically with the new email.