useQuery()
Inofficiell Beta-översättning
Denna sida har översatts av PageTurner AI (beta). Inte officiellt godkänd av projektet. Hittade du ett fel? Rapportera problem →
Hookarna i
@trpc/reactär ett tunt lager ovanpå React Query. För djupgående information om alternativ och användningsmönster, se deras dokumentation om Queries.
tsxfunction useQuery(pathAndInput: [string, TInput?],opts?: UseTRPCQueryOptions;)
tsxfunction useQuery(pathAndInput: [string, TInput?],opts?: UseTRPCQueryOptions;)
Det första argumentet är en [path, input]-tupel – om input är valfritt kan du utelämna , input-delen.
Du kommer att märka att du får autokomplettering på path och automatisk typsäkerhet på input.
Exempel
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>);}