跳至主内容
版本:11.x

获取查询键

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

我们提供了 getQueryKey 辅助函数,它接受一个 routerprocedure 作为参数,使您能够轻松地为原生函数提供正确的查询键。

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 (评论)

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);