useQuery()
The hooks provided by
@trpc/reactare a thin wrapper around React Query. For in-depth information about options and usage patterns, refer to their docs on Queries.
tsxfunction useQuery(pathAndInput: [string, TInput?],opts?: UseTRPCQueryOptions;)
tsxfunction useQuery(pathAndInput: [string, TInput?],opts?: UseTRPCQueryOptions;)
The first argument is a [path, input]-tuple - if the input is optional, you can omit the , input-part.
You'll notice that you get autocompletion on the path and automatic typesafety on the input.
Example​
Backend code
server/routers/_app.tstsximport { 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(({ input }) => {return {greeting: `hello ${input?.text ?? 'world'}`,};})})
server/routers/_app.tstsximport { 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(({ 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.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.tsxtsximport { trpc } from '../utils/trpc';export function MyComponent() {// input is optional, so we don't have to pass second argumentconst 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>);}