How do I revalidate cached data after a mutation in Next.js App Router?

poze 3 months ago361 gadeen

5

I have a Server Component that lists posts, and a Server Action that creates a post. After creating, the list doesn't show the new post until I hard-refresh.

Anviwònman:Next.js 15

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 3 months ago

1 Repons

5
✓
✓ Repons yo aksepte

Call revalidatePath (or revalidateTag) inside the Server Action after the write:

'use server';
import { revalidatePath } from 'next/cache';

export async function createPost(formData: FormData) {
  await db.post.create({ data: { title: String(formData.get('title')) } });
  revalidatePath('/posts');
}

When a Server Action revalidates, Next.js sends the fresh RSC payload back in the same response, so the list updates without a reload.

For data used on many pages, tag your fetches (fetch(url, { next: { tags: ['posts'] } }) or unstable_cache(..., { tags: ['posts'] })) and call revalidateTag('posts').

Konekte pou di lòt moun si li te mache.

answered 3 months ago

Sign in and verify your email to post an answer.