Saltar al contenido principal
Versión: 11.x

getQueryKey

Traducción Beta No Oficial

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

Ofrecemos un ayudante getQueryKey que acepta un router o procedure para que puedas proporcionar fácilmente la clave de consulta correcta a la función nativa.

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 ───────────────────────┘
nota

El tipo de consulta any coincidirá con todas las consultas en la caché solo si el método de react query donde se utiliza emplea fuzzy matching. Consulta TanStack/query#5111 (comment) para más contexto.

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

Mutaciones

De manera similar a las consultas, ofrecemos un getMutationKey para mutaciones. La función subyacente es la misma que getQueryKey (de hecho, técnicamente podrías usar getQueryKey para mutaciones también), siendo la única diferencia semántica.

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