useQueries()
이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →
useQueries 훅을 사용하면 하나의 훅 호출만으로 가변 개수의 쿼리를 동시에 가져올 수 있습니다.
이 훅의 주요 사용 사례는 일반적으로 동일한 유형의 여러 쿼리를 가져오는 것입니다. 예를 들어 할 일 ID 목록을 가져온 후, useQueries 훅에서 이 ID들을 매핑하여 각 할 일의 세부 정보를 가져오는 byId 엔드포인트를 호출할 수 있습니다.
useQueries 훅에서 여러 유형의 쿼리를 가져오는 것은 가능하지만, suspense 옵션을 사용하지 않는 경우 여러 개의 useQuery 호출과 비교해 큰 장점이 없습니다. useQueries는 병렬로 suspense를 트리거하는 반면, 여러 useQuery 호출은 순차적으로 실행되기 때문입니다.
사용법
useQueries 훅은 @tanstack/query useQueries와 동일합니다. 유일한 차이점은 queries 배열을 가진 객체를 전달하는 대신, t 프록시를 받아 쿼리 배열을 반환하는 콜백 함수를 전달한다는 점입니다.
httpBatchLink나 wsLink를 사용하는 경우, 아래 작업은 서버로 향하는 단 1회의 HTTP 호출로 처리됩니다. 또한 내부 프로시저가 Prisma의 findUnique() 같은 기능을 사용하면 자동으로 일괄 처리되어 정확히 1회의 데이터베이스 쿼리만 수행됩니다.
tsximport {trpc } from './utils/trpc';constComponent = (props : {postIds : string[] }) => {constpostQueries =trpc .useQueries ((t ) =>props .postIds .map ((id ) =>t .post .byId ({id })),);return <>{/* [...] */}</>;};
tsximport {trpc } from './utils/trpc';constComponent = (props : {postIds : string[] }) => {constpostQueries =trpc .useQueries ((t ) =>props .postIds .map ((id ) =>t .post .byId ({id })),);return <>{/* [...] */}</>;};
개별 쿼리에 옵션 제공
배열 내 쿼리 호출의 두 번째 매개변수로 enabled, suspense, refetchOnWindowFocus 등 일반적인 쿼리 옵션을 전달할 수 있습니다. 사용 가능한 모든 옵션에 대한 전체 개요는 tanstack useQuery 문서를 참조하세요.
tsximport {trpc } from './utils/trpc';constComponent = () => {const [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }, {enabled : false }),t .greeting ({text : 'world' }),]);constonButtonClick = () => {post .refetch ();};return (<div ><h1 >{post .data &&post .data .title }</h1 ><p >{greeting .data ?.message }</p ><button onClick ={onButtonClick }>Click to fetch</button ></div >);};
tsximport {trpc } from './utils/trpc';constComponent = () => {const [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }, {enabled : false }),t .greeting ({text : 'world' }),]);constonButtonClick = () => {post .refetch ();};return (<div ><h1 >{post .data &&post .data .title }</h1 ><p >{greeting .data ?.message }</p ><button onClick ={onButtonClick }>Click to fetch</button ></div >);};
컨텍스트
기본값을 재정의하기 위해 선택적 React Query 컨텍스트를 전달할 수도 있습니다.
tsxconst [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }),t .greeting ({text : 'world' })],myCustomContext ,);
tsxconst [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }),t .greeting ({text : 'world' })],myCustomContext ,);