Repository navigation
Next.js App Router: How do I refresh server-fetched data after a client-side action? #99995
SummaryHi everyone! I'm working on a project using Next.js App Router, and I've encountered an issue with refreshing data after a client-side action. I'm fetching data inside a Server Component using fetch(). I also have a Client Component that allows users to update a record. After the update succeeds, the database contains the new data, but the UI still displays the old data until I manually refresh the page. I've tried using router.refresh(), but I'm still a little confused about how it interacts with caching and revalidation in the App Router. For example: My questions are:
I'd appreciate an explanation of the recommended pattern and any common pitfalls to avoid. Thanks in advance! Additional informationNo response ExampleNo response |
Replies: 2 comments 1 reply
|
These three do different jobs, and mixing them up is the usual reason people see stale data.
It does not touch the server's cache. If your page reads cached data, you'll just get the cached data again.
Can Yes, and this is the classic gotcha. You update a record, call Invalidate on the server, right after the write succeeds: "use server";
import { revalidatePath } from "next/cache";
export async function updateItem(id: string) {
await db.item.update({
where: { id },
data: { name: "Updated item" },
});
revalidatePath("/items");
}When this runs as a Server Action, Next.js re-renders the affected route with fresh data automatically, so you often don't need If you're calling a Route Handler from a Client Component, invalidate inside the handler once the mutation succeeds, then call |
These three do different jobs, and mixing them up is the usual reason people see stale data.
router.refresh(): A client-side call. It tells Next.js to re-render the current route on the server and merge the result into the page, without wiping client state like form inputs or scroll position.It does not touch the server's cache. If your page reads cached data, you'll just get the cached data again.
revalidatePath(): Runs on the server, in a Server Action or Route Handler. It says "the cached data for this route is out of date, throw it away." Use it when you know which page needs updating.revalidateTag(): Same idea, but by label instead of by route. You tag your fetches, then one call i…