본문으로 건너뛰기
버전: 11.x

useQueries()

useQueries 훅은 단일 훅 호출을 통해 가변 수의 쿼리를 동시에 가져올 수 있습니다.

이러한 훅의 주요 사용 사례는 일반적으로 동일한 유형의 여러 쿼리를 가져오는 것입니다. 예를 들어, 할 일 ID 목록을 가져온 후 useQueries 훅에서 각 ID에 대해 매핑하여 byId 엔드포인트를 호출함으로써 각 할 일의 세부 정보를 가져올 수 있습니다.

노트

useQueries 훅에서 여러 유형을 가져오는 것은 가능하지만, suspense 옵션을 사용하지 않는 한 여러 useQuery 호출을 사용하는 것보다 큰 이점이 없습니다. useQueries를 사용하면 suspense를 병렬로 트리거할 수 있지만, 여러 useQuery 호출은 워터폴 방식으로 실행되기 때문입니다.

사용법

useQueries 훅은 @tanstack/query useQueries와 동일합니다. 유일한 차이점은 queries 배열이 포함된 객체를 전달하는 대신, t 프록시를 받아 쿼리 배열을 반환하는 콜백 함수를 전달한다는 점입니다.

httpBatchLink 또는 wsLink를 사용하는 경우, 아래 코드는 서버로 HTTP 호출이 1회만 이루어집니다. 또한, 기본 프로시저가 Prisma의 findUnique()와 같은 기능을 사용하는 경우 자동으로 배치 처리되어 데이터베이스 쿼리도 정확히 1회만 실행됩니다.

tsx
import { trpc } from './utils/trpc';
 
const Component = (props: { postIds: string[] }) => {
const postQueries = trpc.useQueries((t) =>
props.postIds.map((id) => t.post.byId({ id })),
);
 
return <>{/* [...] */}</>;
};
tsx
import { trpc } from './utils/trpc';
 
const Component = (props: { postIds: string[] }) => {
const postQueries = trpc.useQueries((t) =>
props.postIds.map((id) => t.post.byId({ id })),
);
 
return <>{/* [...] */}</>;
};

개별 쿼리에 옵션 제공

배열 내 쿼리 호출의 두 번째 매개변수에 enabled, suspense, refetchOnWindowFocus 등 일반적인 쿼리 옵션을 전달할 수도 있습니다. 사용 가능한 모든 옵션에 대한 전체 개요는 tanstack useQuery 문서를 참조하세요.

tsx
import { trpc } from './utils/trpc';
 
const Component = () => {
const [post, greeting] = trpc.useQueries((t) => [
t.post.byId({ id: '1' }, { enabled: false }),
t.greeting({ text: 'world' }),
]);
 
const onButtonClick = () => {
post.refetch();
};
 
return (
<div>
<h1>{post.data && post.data.title}</h1>
<p>{greeting.data?.message}</p>
<button onClick={onButtonClick}>Click to fetch</button>
</div>
);
};
tsx
import { trpc } from './utils/trpc';
 
const Component = () => {
const [post, greeting] = trpc.useQueries((t) => [
t.post.byId({ id: '1' }, { enabled: false }),
t.greeting({ text: 'world' }),
]);
 
const onButtonClick = () => {
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 컨텍스트를 전달할 수도 있습니다.

tsx
const [post, greeting] = trpc.useQueries(
(t) => [t.post.byId({ id: '1' }), t.greeting({ text: 'world' })],
myCustomContext,
);
tsx
const [post, greeting] = trpc.useQueries(
(t) => [t.post.byId({ id: '1' }), t.greeting({ text: 'world' })],
myCustomContext,
);