英文:
Can't set cookie in server action Next js 13.4
问题
我尝试在操作中设置一个 cookie,但出现错误:只能在服务器操作或路由处理程序中修改 cookie,但我已经在服务器操作中设置了它们。
路径是 app/actions.ts
import { cookies } from "next/headers";
export async function getCookie() {
"use server";
const cookieStore = cookies();
const calendarId = cookieStore.get("calendarId")?.value;
return Promise.resolve(calendarId);
}
export async function setCookie(id: string) {
"use server";
cookies().set("calendarId", id);
}
我尝试在服务器组件中进行操作,但也不起作用。
以下是我调用 setCookies() 的部分,它位于 app/page.tsx 中,是服务器组件。
if (!calendarId) {
calendar = await prisma.calendar.create({ data: {} });
await setCookie(calendar.id);
}
英文:
Im trying to set a cookie in actions and it giving me an error: Cookies can only be modified in a Server Action or Route Handler, but I have them in the server action.
path is app/actions.ts
import { cookies } from "next/headers";
export async function getCookie() {
"use server";
const cookieStore = cookies();
const calenderId = cookieStore.get("calenderId")?.value;
return Promise.resolve(calenderId);
}
export async function setCookie(id: string) {
"use server";
cookies().set("calenderId", id);
}
I tried to do it in the server component, but that didn't work either.
Here is a part where I call setCookies() it's in app/page.tsx and it's server component
if (!calenderId) {
calender = await prisma.calendar.create({ data: {} });
await setCookie(calender.id);
答案1
得分: 2
以下是已经翻译好的内容:
唯一对我有效的解决方法是在 useEffect
中调用服务器函数,如下所示:
useEffect(() => {
setCookie("newId").then();
}, []);
这是 Next.js 中的一个错误,您可以在此处查看此错误:https://github.com/vercel/next.js/issues/51875
英文:
The only workaround that worked for me was to call the server function inside useEffect
as shown below:
useEffect(() => {
setCookie("newId").then();
}, []);
This is bug in nextjs, you can follow this bug here: https://github.com/vercel/next.js/issues/51875
答案2
得分: 0
不能像普通函数一样调用服务器动作,至少在服务器组件中不行。从文档中了解到:
> 您可以使用以下方法调用服务器动作:
> 使用 action:React 的 action 属性允许在
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论