useQuery()
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
@trpc/react提供的钩子函数是 React Query 的一层薄封装。有关选项和使用模式的详细信息,请参阅其文档中的 查询。
tsxfunction useQuery(pathAndInput: [string, TInput?],opts?: UseTRPCQueryOptions;)
tsxfunction useQuery(pathAndInput: [string, TInput?],opts?: UseTRPCQueryOptions;)
第一个参数是 [path, input] 元组 —— 如果 input 是可选的,可以省略 , input 部分。
你会注意到 path 参数支持自动补全,而 input 参数具备自动类型安全特性。
示例
Backend code
server/routers/_app.tstsximport * as trpc from '@trpc/server';import { z } from 'zod';export const appRouter = trpc.router()// Create procedure at path 'hello'.query('hello', {// using zod schema to validate and infer input valuesinput: z.object({text: z.string().nullish(),}).nullish(),resolve({ input }) {return {greeting: `hello ${input?.text ?? 'world'}`,};},});
server/routers/_app.tstsximport * as trpc from '@trpc/server';import { z } from 'zod';export const appRouter = trpc.router()// Create procedure at path 'hello'.query('hello', {// using zod schema to validate and infer input valuesinput: z.object({text: z.string().nullish(),}).nullish(),resolve({ input }) {return {greeting: `hello ${input?.text ?? 'world'}`,};},});
components/MyComponent.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {// input is optional, so we don't have to pass second argumentconst helloNoArgs = trpc.useQuery(['hello']);const helloWithArgs = trpc.useQuery(['hello', { 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.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {// input is optional, so we don't have to pass second argumentconst helloNoArgs = trpc.useQuery(['hello']);const helloWithArgs = trpc.useQuery(['hello', { 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>);}