Skip to main content
Version: 10.x

设置 React 查询集成

1. 安装依赖

¥ Install dependencies

应安装以下依赖

¥The following dependencies should be installed

bash
npm install @trpc/client @trpc/server @trpc/react-query @tanstack/react-query@4
bash
npm install @trpc/client @trpc/server @trpc/react-query @tanstack/react-query@4

2. 导入你的 AppRouter

¥ Import your AppRouter

AppRouter 类型导入客户端应用。这种类型保存了整个 API 的形状。

¥Import your AppRouter type into the client application. This type holds the shape of your entire API.

ts
import type { AppRouter } from '../server/router';
ts
import type { AppRouter } from '../server/router';
提示

通过使用 import type,你可以确保在编译时删除引用,这意味着你不会无意中将服务器端代码导入到客户端中。欲了解更多信息,请参阅 Typescript 文档

¥By using import type you ensure that the reference will be stripped at compile-time, meaning you don't inadvertently import server-side code into your client. For more information, see the Typescript docs.

3. 创建 tRPC 钩子

¥ Create tRPC hooks

使用 createTRPCReactAppRouter 类型签名创建一组强类型 React hook。

¥Create a set of strongly-typed React hooks from your AppRouter type signature with createTRPCReact.

utils/trpc.ts
ts
import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from '../server/router';
 
export const trpc = createTRPCReact<AppRouter>();
utils/trpc.ts
ts
import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from '../server/router';
 
export const trpc = createTRPCReact<AppRouter>();

4. 添加 tRPC 提供者

¥ Add tRPC providers

创建一个 tRPC 客户端,并将你的应用封装在 tRPC Provider 中,如下所示。你还需要设置并连接 React Query,即 他们更深入地记录

¥Create a tRPC client, and wrap your application in the tRPC Provider, as below. You will also need to set up and connect React Query, which they document in more depth.

提示

如果你已经在应用中使用 React Query,则应该重新使用已有的 QueryClientQueryClientProvider

¥If you already use React Query in your application, you should re-use the QueryClient and QueryClientProvider you already have.

App.tsx
tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { httpBatchLink } from '@trpc/client';
import React, { useState } from 'react';
import { trpc } from './utils/trpc';
export function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
httpBatchLink({
url: 'http://localhost:3000/trpc',
// You can pass any HTTP headers you wish here
async headers() {
return {
authorization: getAuthCookie(),
};
},
}),
],
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}
App.tsx
tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { httpBatchLink } from '@trpc/client';
import React, { useState } from 'react';
import { trpc } from './utils/trpc';
export function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
httpBatchLink({
url: 'http://localhost:3000/trpc',
// You can pass any HTTP headers you wish here
async headers() {
return {
authorization: getAuthCookie(),
};
},
}),
],
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}
注意

在创建 queryClientTRPCClient 时使用 useState(而不是在组件外部声明它们)的原因是为了确保在使用 SSR 时每个请求都获得唯一的客户端。如果你使用客户端渲染,那么你可以根据需要移动它们。

¥The reason for using useState in the creation of the queryClient and the TRPCClient, as opposed to declaring them outside of the component, is to ensure that each request gets a unique client when using SSR. If you use client side rendering then you can move them if you wish.

5. 获取数据

¥ Fetch data

你现在可以使用 tRPC React Query 集成来调用 API 上的查询和变更。

¥You can now use the tRPC React Query integration to call queries and mutations on your API.

pages/IndexPage.tsx
tsx
import { trpc } from '../utils/trpc';
 
export default function IndexPage() {
const userQuery = trpc.getUser.useQuery({ id: 'id_bilbo' });
const userCreator = trpc.createUser.useMutation();
 
return (
<div>
<p>{userQuery.data?.name}</p>
 
<button onClick={() => userCreator.mutate({ name: 'Frodo' })}>
Create Frodo
</button>
</div>
);
}
pages/IndexPage.tsx
tsx
import { trpc } from '../utils/trpc';
 
export default function IndexPage() {
const userQuery = trpc.getUser.useQuery({ id: 'id_bilbo' });
const userCreator = trpc.createUser.useMutation();
 
return (
<div>
<p>{userQuery.data?.name}</p>
 
<button onClick={() => userCreator.mutate({ name: 'Frodo' })}>
Create Frodo
</button>
</div>
);
}