跳至主要内容
版本:11.x

getQueryKey

我们提供了一个 getQueryKey 帮助程序,它接受一个 routerprocedure,以便您可以轻松地为原生函数提供正确的查询键。

tsx
// Queries
function getQueryKey(
procedure: AnyQueryProcedure,
input?: DeepPartial<TInput>,
type?: QueryType; /** @default 'any' */
): TRPCQueryKey;
// Routers
function getQueryKey(
router: AnyRouter,
): TRPCQueryKey;
// Mutations
function getQueryKey(
procedure: AnyMutationProcedure,
): TRPCQueryKey;
type QueryType = "query" | "infinite" | "any";
// for useQuery ──┘ │ │
// for useInfiniteQuery ────┘ │
// will match all ───────────────────────┘
tsx
// Queries
function getQueryKey(
procedure: AnyQueryProcedure,
input?: DeepPartial<TInput>,
type?: QueryType; /** @default 'any' */
): TRPCQueryKey;
// Routers
function getQueryKey(
router: AnyRouter,
): TRPCQueryKey;
// Mutations
function getQueryKey(
procedure: AnyMutationProcedure,
): 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(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(postListKey);
// Set some query defaults for an entire router
const postKey = getQueryKey(trpc.post);
queryClient.setQueryDefaults(postKey, { staleTime: 30 * 60 * 1000 });
// ...
}