tRPC - nextjs - 应用程序路由器 - 使用 useSuspenseQuery 时构建因超时错误而失败

问题描述 投票:0回答:1

我创建了 T3-app,但我的构建因超时错误而失败。 如果我改变这一行:

const [leads] = api.lead.getLeads.useSuspenseQuery();

const { data: leads } = api.lead.getLeads.useQuery();

构建过程。

如何使用 useSuspenceQuery? 我做错了什么? 除了没有加载/错误状态之外,suspenceQuery 还有其他好处吗?

完整错误:

Failed to build /page: / (attempt 1 of 3) because it took more than 60 seconds. Retrying again shortly.
Failed to build /page: / (attempt 2 of 3) because it took more than 60 seconds. Retrying again shortly.
Failed to build /page: / after 3 attempts.
Export encountered an error on /page: /, exiting the build.
 ⨯ Static worker exited with code: 1 and signal: null

这是页面组件:

import { api, HydrateClient } from "@/trpc/server";
import { Leads } from "./_components/Leads/Leads";

export default async function Home() {
  await api.lead.getLeads.prefetch();

  return (
    <HydrateClient>
      <Leads />
    </HydrateClient>
  );
}

这是线索表组件,其中

useSuspenseQuery
位于:

"use client";

import { api } from "@/trpc/react";
import { Table } from "../../UI";
import { columns } from "./LeadsTable.columns";

export const LeadsTable = () => {
  const [leads] = api.lead.getLeads.useSuspenseQuery();

  return (
    <Table
      rows={leads}
      columns={columns}
      initialState={{
        sorting: {
          sortModel: [
            {
              field: "id",
              sort: "desc",
            },
          ],
        },
      }}
    />
  );
};

这是整个仓库:https://github.com/ItayTur/sohnim-io

next.js trpc t3
1个回答
0
投票

以下是一些步骤和注意事项,可帮助您正确使用

useSuspenseQuery
并避免构建超时

使用

useSuspenseQuery
时,组件期望数据立即可用,如果没有,它将暂停渲染,直到获取数据。

主页组件

import { api, HydrateClient } from "@/trpc/server";
import { Leads } from "./_components/Leads/Leads";
import { Suspense } from "react";

export default async function Home() {
  await api.lead.getLeads.prefetch();

  return (
    <HydrateClient>
      // you can change the loading div to some nice loader component or else
      <Suspense fallback={<div>Loading...</div>}>
        <Leads />
      </Suspense>
    </HydrateClient>
  );
}

LeadsTable 组件

"use client";

import { api } from "@/trpc/react";
import { Table } from "../../UI";
import { columns } from "./LeadsTable.columns";

export const LeadsTable = () => {
  const [leads] = api.lead.getLeads.useSuspenseQuery();

  return (
    <Table
      rows={leads}
      columns={columns}
      initialState={{
        sorting: {
          sortModel: [
            {
              field: "id",
              sort: "desc",
            },
          ],
        },
      }}
    />
  );
};

说明:

  1. Suspense Fallback

    Home
    组件现在包含
    Suspense
    后备。这确保了构建过程和用户体验在获取数据时有一个后备 UI。

  2. useSuspenseQuery

    LeadsTable
    组件使用
    useSuspenseQuery
    来获取数据。这确保组件将暂停渲染,直到数据可用。

其他注意事项:

  • API 性能:确保您的 API 性能良好且响应快速。 API 响应缓慢可能会导致构建过程超时。

  • 错误处理:考虑添加错误处理来管理数据获取失败的情况。这可以使用

    useSuspenseQuery
    钩子的错误状态来完成。

© www.soinside.com 2019 - 2024. All rights reserved.