跳至主内容
版本:10.x

getQueryKey

非官方测试版翻译

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

我们提供了 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 (评论)

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 });
// ...
}