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>);}