メインコンテンツへスキップ
バージョン: 11.x

getQueryKey

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

routerprocedureを受け入れるgetQueryKeyヘルパーを提供しています。これにより、ネイティブ関数に正しいクエリキーを簡単に渡せます。

tsx
// Queries
function getQueryKey(
procedure: AnyQueryProcedure,
input?: DeepPartial<TInput>,
type?: QueryType; /** @default 'any' */
): TRPCQueryKey;
// Routers
function getQueryKey(
router: AnyRouter,
): 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;
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 });
// ...
}

ミューテーション

クエリと同様に、ミューテーション用のgetMutationKeyも提供しています。内部的にはgetQueryKeyと同じ関数ですが(技術的にはgetQueryKeyをミューテーションにも使用可能)、意味的な違いがあります。

tsx
function getMutationKey(procedure: AnyMutationProcedure): TRPCMutationKey;
tsx
function getMutationKey(procedure: AnyMutationProcedure): TRPCMutationKey;