next.js SSGHelpers和GetStaticProps关于参数的问题

gmol1639  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(104)

我试图使用createProxySSGHelpers预取数据与trpc在一个项目中,我的工作,我有一个很难弄清楚为什么我不能得到我的id从url参数是回来未定义时,我可以看到它在我的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 helper函数:

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”)抛出新的Error(“No householdId.”)行,如果删除了,则表示undefined不能被序列化为json。我是错误地抓住了参数还是我错过了其他东西?
谢谢

oxalkeyp

oxalkeyp1#

我认为householdId可以是string | string[] | undefined,也许这就是if不起作用的原因。
尝试做:

const householdId = context.params?.householdId as string;

相关问题