英文:
Using NextJS revalidateTag with Prisma in App Router and Server Components
问题
在Next.js 13中,使用App Router,可以在不进行fetch调用的情况下使用revalidatePath吗?我正在尝试避免使用router.refresh()进行完全刷新,而是只在特定标签上进行刷新。我了解这在使用fetch时是可能的,但由于使用了服务器组件,这种情况下不需要API路由。
例如:
import { prisma } from "@/db";
export default async function Page() {
const addUser = async () => {
"use server";
await prisma.user.create({
data: {
email: faker.internet.email()
}
});
return {
revalidateTag: ["db"] <<<<<<---------
}
};
return (
<>
<form action={addUser}>
<input
...
/>
</form>
<div>{...最新的用户数据}</div>
</>
);
}
英文:
Is it possible in Next 13 with the App Router, to use revalidatePath without making a fetch call? I'm trying to avoid a full refresh with router.refresh() and rather just refresh on specific tags. I understand this is possible with fetch, but due to using server components an API route isn't needed in this use case.
For example:
import { prisma } from "@/db";
export default async function Page() {
const addUser = async() => {
"use server";
await prisma.user.create({
data: {
email: faker.internet.email()
}
});
return {
revalidateTag: ["db"] <<<<<---------
}
};
return(
<>
<form action={ addUser }>
<input
...
/>
</form>
<div>{ ...up to date user data }</div>
</>
);
}
答案1
得分: 2
我遇到了相同的问题。我找到的最佳方法是在服务器操作完成后使用 revalidatePath。
import { prisma } from "@/db";
import { revalidatePath } from 'next/cache';
export default async function Page() {
const addUser = async () => {
"use server";
await prisma.user.create({
data: {
email: faker.internet.email()
}
});
revalidatePath("/") //无论从哪个路径调用它
};
return (
<>
<form action={addUser}>
<input
...
/>
</form>
<div>{...最新用户数据}</div>
</>
);
}
您可以在此处了解更多信息:https://nextjs.org/docs/app/api-reference/functions/revalidatePath
英文:
I'm having the same issue. The best approach I could find is to use revalidatePath inside the server action after everything is done.
import { prisma } from "@/db";
import { revalidatePath } from 'next/cache'
export default async function Page() {
const addUser = async() => {
"use server";
await prisma.user.create({
data: {
email: faker.internet.email()
}
});
revalidatePath("/") //whatever path you are calling it from
};
return(
<>
<form action={ addUser }>
<input
...
/>
</form>
<div>{ ...up to date user data }</div>
</>
);
}
You can learn more about it here: https://nextjs.org/docs/app/api-reference/functions/revalidatePath
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论