我正在尝试使用createProxySSGHelpers在我正在工作的项目中与trpc预取数据,并且我很难弄清楚为什么我无法从url参数中获得我的id,当我可以在我的url栏中看到它时未定义。
这是我的getStaticProps正在尝试预取:
import { generateSSGHelper } from "~/server/helpers/ssgHelper";
import type { NextPage, GetStaticProps } from "next";
export const getStaticProps: GetStaticProps = async (context) => {
const ssg = generateSSGHelper();
const householdId = context.params?.householdId;
if (typeof householdId !== "string") throw new Error("No householdId.");
await ssg.household.getHouseholdInfo.prefetch({ householdId });
return {
props: {
trpcState: ssg.dehydrate(),
householdId,
},
};
};
export const getStaticPaths = () => {
return { paths: [], fallback: "blocking" };
};
下面是我的SSG辅助函数:
import { createProxySSGHelpers } from "@trpc/react-query/ssg";
import { appRouter } from "~/server/api/root";
import { prisma } from "~/server/db";
import superjson from "superjson";
import { type Session } from "next-auth";
export const generateSSGHelper = () =>
createProxySSGHelpers({
router: appRouter,
ctx: { prisma, session: null },
transformer: superjson,
});
和我的TRPC路由器调用:
getHouseholdInfo: protectedProcedure
.input(z.object({ householdId: z.string() }))
.query(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
return ctx.prisma.household.findUnique({
where: {
householdId: input.householdId,
},
select: {
name: true,
members: true,
invitedList: true,
householdId: true,
_count: true,
},
});
}),
在if (typeof householdId !== "string") throw new error ("No householdId.")行抛出错误,如果删除该行,则表示undefined无法被序列化为json。我是否错误地抓取了参数,或者我是否遗漏了其他内容?
谢谢。
我认为housedid可以是string | string[] | undefined
,所以也许这就是if不起作用的原因。
尝试:
const householdId = context.params?.householdId as string;