useQuery()
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
Los hooks proporcionados por @trpc/react-query son una capa delgada sobre @tanstack/react-query. Para información detallada sobre opciones y patrones de uso, consulta su documentación sobre consultas.
tsxfunction useQuery(input: TInput,opts?: UseTRPCQueryOptions;)interface UseTRPCQueryOptionsextends UseQueryOptions {trpc: {ssr?: boolean;abortOnUnmount?: boolean;context?: Record<string, unknown>;}}
tsxfunction useQuery(input: TInput,opts?: UseTRPCQueryOptions;)interface UseTRPCQueryOptionsextends UseQueryOptions {trpc: {ssr?: boolean;abortOnUnmount?: boolean;context?: Record<string, unknown>;}}
Dado que UseTRPCQueryOptions extiende UseQueryOptions de @tanstack/react-query, puedes usar cualquiera de sus opciones como enabled, refetchOnWindowFocus, etc. También tenemos opciones específicas de trpc que te permiten activar o desactivar comportamientos específicos a nivel de procedimiento:
-
trpc.ssr: Si tienesssr: trueen tu configuración global, puedes establecer esto en false para desactivar ssr en esta consulta específica. Nota: Esto no funciona al revés, es decir, no puedes activar ssr en un procedimiento si tu configuración global está en false. -
trpc.abortOnUnmount: Sobrescribe la configuración global para activar o desactivar la cancelación de consultas al desmontar componentes. -
trpc.context: Añade metadatos adicionales que podrían usarse en Links.
Si necesitas establecer opciones pero no quieres pasar ningún input, puedes pasar undefined.
Notarás que obtienes autocompletado para el input basado en lo que has configurado en tu esquema de input en el backend.
Ejemplo
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((opts) => {return {greeting: `hello ${opts.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((opts) => {return {greeting: `hello ${opts.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>);}