跳到主要內容
版本:11.x

useQuery()

注意

@trpc/react-query 提供的 hooks 是 @tanstack/react-query 的簡潔包裝。如需選項和使用模式的深入資訊,請參閱其文件中的 查詢

tsx
function useQuery(
input: TInput,
opts?: UseTRPCQueryOptions;
)
interface UseTRPCQueryOptions
extends UseQueryOptions {
trpc: {
ssr?: boolean;
abortOnUnmount?: boolean;
context?: Record<string, unknown>;
}
}
tsx
function useQuery(
input: TInput,
opts?: UseTRPCQueryOptions;
)
interface UseTRPCQueryOptions
extends UseQueryOptions {
trpc: {
ssr?: boolean;
abortOnUnmount?: boolean;
context?: Record<string, unknown>;
}
}

由於 UseTRPCQueryOptions 延伸了 @tanstack/react-query 的 UseQueryOptions,因此您可以在此處使用任何選項,例如 enabledrefetchOnWindowFocus 等。我們還有一些 trpc 特定的選項,讓您可以在每個程序層級選擇加入或退出特定行為

  • trpc.ssr如果您的 全域設定 中有 ssr: true,您可以將此設定為 false 以停用此特定查詢的 ssr。請注意,反之則不行,也就是說,如果您的全域設定設為 false,您無法在程序上啟用 ssr。
  • trpc.abortOnUnmount覆寫 全域設定,並選擇在卸載時中斷查詢或不中斷查詢。
  • trpc.context新增額外的元資料,可於 連結 中使用。
提示

如果您需要設定任何選項,但不想傳遞任何輸入,您可以傳遞 undefined

您會注意到,根據您在後端 input 架構中設定的內容,您可以在 input 上取得自動完成。

範例

後端程式碼
server/routers/_app.ts
tsx
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
export const t = initTRPC.create();
export const appRouter = t.router({
// Create procedure at path 'hello'
hello: t.procedure
// using zod schema to validate and infer input values
.input(
z
.object({
text: z.string().nullish(),
})
.nullish(),
)
.query((opts) => {
return {
greeting: `hello ${opts.input?.text ?? 'world'}`,
};
}),
});
server/routers/_app.ts
tsx
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
export const t = initTRPC.create();
export const appRouter = t.router({
// Create procedure at path 'hello'
hello: t.procedure
// using zod schema to validate and infer input values
.input(
z
.object({
text: z.string().nullish(),
})
.nullish(),
)
.query((opts) => {
return {
greeting: `hello ${opts.input?.text ?? 'world'}`,
};
}),
});
components/MyComponent.tsx
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
// input is optional, so we don't have to pass second argument
const helloNoArgs = trpc.hello.useQuery();
const helloWithArgs = trpc.hello.useQuery({ text: 'client' });
return (
<div>
<h1>Hello World Example</h1>
<ul>
<li>
helloNoArgs ({helloNoArgs.status}):{' '}
<pre>{JSON.stringify(helloNoArgs.data, null, 2)}</pre>
</li>
<li>
helloWithArgs ({helloWithArgs.status}):{' '}
<pre>{JSON.stringify(helloWithArgs.data, null, 2)}</pre>
</li>
</ul>
</div>
);
}
components/MyComponent.tsx
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
// input is optional, so we don't have to pass second argument
const helloNoArgs = trpc.hello.useQuery();
const helloWithArgs = trpc.hello.useQuery({ text: 'client' });
return (
<div>
<h1>Hello World Example</h1>
<ul>
<li>
helloNoArgs ({helloNoArgs.status}):{' '}
<pre>{JSON.stringify(helloNoArgs.data, null, 2)}</pre>
</li>
<li>
helloWithArgs ({helloWithArgs.status}):{' '}
<pre>{JSON.stringify(helloWithArgs.data, null, 2)}</pre>
</li>
</ul>
</div>
);
}