getQueryKey
We provide a getQueryKey helper that accepts a router or procedure so that you can easily provide the native function the correct query key.
tsx// Queriesdeclare functiongetQueryKey (procedure :AnyQueryProcedure ,input ?:DeepPartial <TInput >,type ?:QueryType , /** @default 'any' */):TRPCQueryKey ;// Routersdeclare functiongetQueryKey (router :AnyRouter ,):TRPCQueryKey ;typeQueryType = "query" | "infinite" | "any";// for useQuery ──┘ │ │// for useInfiniteQuery ────┘ │// will match all ───────────────────────┘
tsx// Queriesdeclare functiongetQueryKey (procedure :AnyQueryProcedure ,input ?:DeepPartial <TInput >,type ?:QueryType , /** @default 'any' */):TRPCQueryKey ;// Routersdeclare functiongetQueryKey (router :AnyRouter ,):TRPCQueryKey ;typeQueryType = "query" | "infinite" | "any";// for useQuery ──┘ │ │// for useInfiniteQuery ────┘ │// will match all ───────────────────────┘
note
The query type any will match all queries in the cache only if the react query method where it's used uses fuzzy matching. See TanStack/query#5111 (comment) for more context.
tsximport {useIsFetching ,useQueryClient } from '@tanstack/react-query';import {getQueryKey } from '@trpc/react-query';import {trpc } from './utils/trpc';functionMyComponent () {constqueryClient =useQueryClient ();constposts =trpc .post .list .useQuery ();// See if a query is fetchingconstpostListKey =getQueryKey (trpc .post .list ,undefined , 'query');constisFetching =useIsFetching ({queryKey :postListKey });// Set some query defaults for an entire routerconstpostKey =getQueryKey (trpc .post );queryClient .setQueryDefaults (postKey , {staleTime : 30 * 60 * 1000 });// ...}
tsximport {useIsFetching ,useQueryClient } from '@tanstack/react-query';import {getQueryKey } from '@trpc/react-query';import {trpc } from './utils/trpc';functionMyComponent () {constqueryClient =useQueryClient ();constposts =trpc .post .list .useQuery ();// See if a query is fetchingconstpostListKey =getQueryKey (trpc .post .list ,undefined , 'query');constisFetching =useIsFetching ({queryKey :postListKey });// Set some query defaults for an entire routerconstpostKey =getQueryKey (trpc .post );queryClient .setQueryDefaults (postKey , {staleTime : 30 * 60 * 1000 });// ...}
Mutations
Similarly to queries, we provide a getMutationKey for mutations. The underlying function is the same as getQueryKey (in fact, you could technically use getQueryKey for mutations as well), the only difference is in semantics.
tsximport { getMutationKey } from '@trpc/react-query';const mutationKey = getMutationKey(trpc.user.create);
tsximport { getMutationKey } from '@trpc/react-query';const mutationKey = getMutationKey(trpc.user.create);