getQueryKey
我们提供了一个接受 router 或 procedure 的 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// Queriesfunction getQueryKey(procedure: AnyQueryProcedure,input?: DeepPartial<TInput>,type?: QueryType; /** @default 'any' */): TRPCQueryKey;// Routersfunction getQueryKey(router: AnyRouter,): TRPCQueryKey;type QueryType = "query" | "infinite" | "any";// for useQuery ──┘ │ │// for useInfiniteQuery ────┘ │// will match all ───────────────────────┘
tsx// Queriesfunction getQueryKey(procedure: AnyQueryProcedure,input?: DeepPartial<TInput>,type?: QueryType; /** @default 'any' */): TRPCQueryKey;// Routersfunction getQueryKey(router: AnyRouter,): TRPCQueryKey;type QueryType = "query" | "infinite" | "any";// for useQuery ──┘ │ │// for useInfiniteQuery ────┘ │// will match all ───────────────────────┘
仅当使用查询类型 any 的 react query 方法使用模糊匹配时,查询类型 any 才会匹配缓存中的所有查询。有关更多背景信息,请参阅 TanStack/query#5111(注释)。
¥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';function MyComponent() {const queryClient = useQueryClient();const posts = trpc.post.list.useQuery();// See if a query is fetchingconst postListKey = getQueryKey(trpc.post.list, undefined, 'query');const isFetching = useIsFetching(postListKey);// Set some query defaults for an entire routerconst postKey = 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';function MyComponent() {const queryClient = useQueryClient();const posts = trpc.post.list.useQuery();// See if a query is fetchingconst postListKey = getQueryKey(trpc.post.list, undefined, 'query');const isFetching = useIsFetching(postListKey);// Set some query defaults for an entire routerconst postKey = getQueryKey(trpc.post);queryClient.setQueryDefaults(postKey, { staleTime: 30 * 60 * 1000 });// ...}
修改
¥Mutations
与查询类似,我们为突变提供了 getMutationKey。底层函数与 getQueryKey 相同(事实上,从技术上讲,你也可以使用 getQueryKey 进行突变),唯一的区别在于语义。
¥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.
tsxfunction getMutationKey(procedure: AnyMutationProcedure): TRPCMutationKey;
tsxfunction getMutationKey(procedure: AnyMutationProcedure): TRPCMutationKey;