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

getQueryKey

router 또는 procedure를 받아들이는 getQueryKey 헬퍼를 제공하므로, 네이티브 함수에 올바른 쿼리 키를 쉽게 제공할 수 있습니다.

tsx
// Queries
declare function getQueryKey(
procedure: AnyQueryProcedure,
input?: DeepPartial<TInput>,
type?: QueryType, /** @default 'any' */
): TRPCQueryKey;
 
// Routers
declare function getQueryKey(
router: AnyRouter,
): TRPCQueryKey;
 
type QueryType = "query" | "infinite" | "any";
// for useQuery ──┘ │ │
// for useInfiniteQuery ────┘ │
// will match all ───────────────────────┘
tsx
// Queries
declare function getQueryKey(
procedure: AnyQueryProcedure,
input?: DeepPartial<TInput>,
type?: QueryType, /** @default 'any' */
): TRPCQueryKey;
 
// Routers
declare function getQueryKey(
router: AnyRouter,
): TRPCQueryKey;
 
type QueryType = "query" | "infinite" | "any";
// for useQuery ──┘ │ │
// for useInfiniteQuery ────┘ │
// will match all ───────────────────────┘
노트

쿼리 타입 any는 사용된 react query 메서드가 퍼지 매칭을 사용하는 경우에만 캐시의 모든 쿼리와 일치합니다. 자세한 컨텍스트는 TanStack/query#5111 (comment)를 참조하세요.

tsx
import { useIsFetching, useQueryClient } from '@tanstack/react-query';
import { getQueryKey } from '@trpc/react-query';
import { trpc } from './utils/trpc';
 
function MyComponent() {
const queryClient = useQueryClient();
 
const posts = trpc.post.list.useQuery();
 
// See if a query is fetching
const postListKey = getQueryKey(trpc.post.list, undefined, 'query');
const isFetching = useIsFetching({ queryKey: postListKey });
 
// Set some query defaults for an entire router
const postKey = getQueryKey(trpc.post);
queryClient.setQueryDefaults(postKey, { staleTime: 30 * 60 * 1000 });
 
// ...
}
tsx
import { useIsFetching, useQueryClient } from '@tanstack/react-query';
import { getQueryKey } from '@trpc/react-query';
import { trpc } from './utils/trpc';
 
function MyComponent() {
const queryClient = useQueryClient();
 
const posts = trpc.post.list.useQuery();
 
// See if a query is fetching
const postListKey = getQueryKey(trpc.post.list, undefined, 'query');
const isFetching = useIsFetching({ queryKey: postListKey });
 
// Set some query defaults for an entire router
const postKey = getQueryKey(trpc.post);
queryClient.setQueryDefaults(postKey, { staleTime: 30 * 60 * 1000 });
 
// ...
}

뮤테이션

쿼리와 마찬가지로 뮤테이션용 getMutationKey도 제공합니다. 내부 함수는 getQueryKey와 동일하며(실제로 뮤테이션에도 getQueryKey를 사용할 수 있음), 유일한 차이는 의미상의 구분입니다.

tsx
import { getMutationKey } from '@trpc/react-query';
const mutationKey = getMutationKey(trpc.user.create);
tsx
import { getMutationKey } from '@trpc/react-query';
const mutationKey = getMutationKey(trpc.user.create);