useQuery()
이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →
useQuery는 데이터 페칭을 위한 핵심 훅입니다. @tanstack/react-query의 useQuery와 유사하게 동작하지만, trpc 전용 옵션과 스트리밍 같은 추가 기능을 제공합니다.
옵션과 사용 패턴에 대한 상세 정보는 TanStack Query 문서의 쿼리 섹션을 참조하세요.
시그니처
tsxdeclare functionuseQuery (input :TInput |SkipToken ,opts ?:UseTRPCQueryOptions ,): void;interfaceUseTRPCQueryOptions extendsUseQueryOptions {trpc : {ssr ?: boolean;abortOnUnmount ?: boolean;context ?:Record <string, unknown>;}}
tsxdeclare functionuseQuery (input :TInput |SkipToken ,opts ?:UseTRPCQueryOptions ,): void;interfaceUseTRPCQueryOptions extendsUseQueryOptions {trpc : {ssr ?: boolean;abortOnUnmount ?: boolean;context ?:Record <string, unknown>;}}
UseTRPCQueryOptions는 @tanstack/react-query의 UseQueryOptions를 확장하므로 enabled, refetchOnWindowFocus 같은 옵션을 모두 사용할 수 있습니다. 또한 프로시저 단위로 특정 동작을 선택/해제할 수 있는 trpc 전용 옵션이 존재합니다:
-
trpc.ssr: 글로벌 설정에서ssr: true로 설정한 경우, 이 옵션을 false로 지정하면 해당 쿼리에 대해 SSR을 비활성화할 수 있습니다. 단, 반대의 경우는 작동하지 않습니다. 즉, 글로벌 설정이 false인 경우 프로시저에서 SSR을 활성화할 수 없습니다. -
trpc.abortOnUnmount: 글로벌 설정을 재정의하고 컴포넌트 언마운트 시 쿼리 중단을 선택하거나 해제합니다. -
trpc.context: 링크에서 사용할 수 있는 추가 메타데이터를 추가합니다.
입력값을 전달하지 않고 옵션만 설정해야 할 경우 undefined를 전달할 수 있습니다.
백엔드의 input 스키마 설정에 기반해 input에 대한 자동 완성 기능이 제공되는 것을 확인할 수 있습니다.
사용 예시
Backend code
server/routers/_app.tstsximport {initTRPC } from '@trpc/server';import {z } from 'zod';export constt =initTRPC .create ();export constappRouter =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'}`,};}),});export typeAppRouter = typeofappRouter ;
server/routers/_app.tstsximport {initTRPC } from '@trpc/server';import {z } from 'zod';export constt =initTRPC .create ();export constappRouter =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'}`,};}),});export typeAppRouter = typeofappRouter ;
components/MyComponent.tsxtsximport {trpc } from '../utils/trpc';export functionMyComponent () {// input is optional, so we don't have to pass second argumentconsthelloNoArgs =trpc .hello .useQuery ();consthelloWithArgs =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 functionMyComponent () {// input is optional, so we don't have to pass second argumentconsthelloNoArgs =trpc .hello .useQuery ();consthelloWithArgs =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 >);}
async generator를 사용한 스트리밍 응답
v11부터 httpBatchStreamLink 사용 시 스트리밍 쿼리를 지원합니다.
쿼리에서 async generator를 반환할 경우, 다음과 같은 현상이 발생합니다:
-
응답 수신 시 업데이트되는 반복자(iterator) 결과를 배열 형태로
data속성에서 확인 가능 -
첫 청크 수신 시
status가success로 변경됨 -
마지막 청크 수신 전까지
fetchStatus속성은fetching상태 유지
예시
server/routers/_app.tstsximport {initTRPC } from '@trpc/server';constt =initTRPC .create ();constappRouter =t .router ({iterable :t .procedure .query (async function* () {for (leti = 0;i < 3;i ++) {await newPromise ((resolve ) =>setTimeout (resolve , 500));yieldi ;}}),});export typeAppRouter = typeofappRouter ;
server/routers/_app.tstsximport {initTRPC } from '@trpc/server';constt =initTRPC .create ();constappRouter =t .router ({iterable :t .procedure .query (async function* () {for (leti = 0;i < 3;i ++) {await newPromise ((resolve ) =>setTimeout (resolve , 500));yieldi ;}}),});export typeAppRouter = typeofappRouter ;
components/MyComponent.tsxtsximportReact , {Fragment } from 'react';import {trpc } from '../utils/trpc';export functionMyComponent () {constresult =trpc .iterable .useQuery ();return (<div >{result .data ?.map ((chunk ,index ) => (<Fragment key ={index }>{chunk }</Fragment >))}</div >);}
components/MyComponent.tsxtsximportReact , {Fragment } from 'react';import {trpc } from '../utils/trpc';export functionMyComponent () {constresult =trpc .iterable .useQuery ();return (<div >{result .data ?.map ((chunk ,index ) => (<Fragment key ={index }>{chunk }</Fragment >))}</div >);}
스트리밍 중인 result 속성:
status | fetchStatus | data |
|---|---|---|
'pending' | 'fetching' | undefined |
'success' | 'fetching' | [] |
'success' | 'fetching' | [0] |
'success' | 'fetching' | [0, 1] |
'success' | 'fetching' | [0, 1, 2] |
'success' | 'idle' | [0, 1, 2] |