译零 TransZero · TanStack Query v4 中文文档
主站

Query Key Factory

Typesafe query key management with auto-completion features. Focus on writing and invalidating queries without the hassle of remembering how you've set up a key for a specific query!

Installation

You can install Query Key Factory via NPM.

Shell
1$ npm i @lukemorales/query-key-factory2# or3$ pnpm add @lukemorales/query-key-factory4# or5$ yarn add @lukemorales/query-key-factory

Quick start

Start by defining the query keys for your app:

Declare everything in a single file

TypeScript
1import { createQueryKeyStore } from "@lukemorales/query-key-factory";2 3export const queryKeys = createQueryKeyStore({4  users: null,5  todos: {6    detail: (todoId: string) => [todoId],7    list: (filters: TodoFilters) => ({8      queryKey: [{ filters }],9      queryFn: (ctx) => api.getTodos({ filters, page: ctx.pageParam }),10    }),11  },12});

Fine-grained declaration by features

TypeScript
1import {2  createQueryKeys,3  mergeQueryKeys,4} from "@lukemorales/query-key-factory";5 6// my-api/users.ts7export const usersKeys = createQueryKeys("users");8 9// my-api/todos.ts10export const todosKeys = createQueryKeys("todos", {11  detail: (todoId: string) => [todoId],12  list: (filters: TodoFilters) => ({13    queryKey: [{ filters }],14    queryFn: (ctx) => api.getTodos({ filters, page: ctx.pageParam }),15  }),16});17 18// my-api/index.ts19export const queryKeys = mergeQueryKeys(usersKeys, todosKeys);

Use throughout your codebase as the single source for writing the query keys for your cache management:

TypeScript
1import { queryKeys, completeTodo, fetchSingleTodo } from "../my-api";2 3export function Todo({ todoId }) {4  const queryClient = useQueryClient();5 6  const query = useQuery(queryKeys.todos.detail(todoId));7 8  const mutation = useMutation({9    mutationFn: completeTodo,10    onSuccess: () => {11      // Invalidate and refetch12      queryClient.invalidateQueries({13        queryKey: queryKeys.todos.list.queryKey,14      });15    },16  });17 18  return (19    <div>20      <h1>{query.data?.title}</h1>2122      <p>{query.data?.description}</p>2324      <button25        onClick={() => {26          mutation.mutate({ todoId });27        }}28      >29        Complete Todo30      </button>31    </div>32  );33}

Check the complete documentation on GitHub.

本页为 TanStack Query 文档(React 版)的非官方中文翻译,原文由上游团队维护,遵循 MIT 许可。 译文如有偏差,以英文原文为准。

本页译文取自社区中文版 react-query-web-i18n(MIT),非本站翻译,已停止更新,内容可能与当前 API 有出入。

译自上游 (未记录版本)