Next.js
/Advanced
Data Mutations
Definition
The end-to-end process of changing data on the server (creating, updating, deleting) and ensuring the client UI perfectly reflects those changes.
Explain Like I'm New
If you add a new 'Todo' item to the database, the database updates, but the user's screen will still show the old list. You must 'mutate' the data, and then immediately tell Next.js to purge the cache and refresh the screen.
Real World Example
A user clicks 'Delete' on an article. The Server Action deletes the row in PostgreSQL, and then calls `revalidatePath('/articles')` to instantly refresh the UI so the article visually disappears.
Common Use Cases
- •CRUD Operations
- •Interactive applications
Interactive Example
// app/actions.ts 'use server'; import { revalidatePath } from 'next/cache'; import db from '@/lib/db'; export async function deleteTodo(id: string) { // 1. Mutate the data in the database await db.todo.delete({ where: { id } }); // 2. Purge the cache for the /todos page so it fetches fresh data! revalidatePath('/todos'); } // app/todos/page.tsx import { deleteTodo } from '@/actions'; export default function TodoList({ todos }) { return ( <ul> {todos.map(todo => ( <li key={todo.id}> {todo.title} {/* Inline Server Action using bind! */} <form action={deleteTodo.bind(null, todo.id)}> <button type="submit">Delete</button> </form> </li> ))} </ul> ) }
Interview Questions
basic
- What is the primary Next.js function used to refresh the UI after a Server Action mutates data?
intermediate
- How do you show a 'Loading...' state on a submit button while a Server Action mutation is running?