译零 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    completed: null,7    search: (query: string, limit = 15) => [query, limit],8    byId: (todoId: string) => ({ todoId }),9  },10})

Fine-grained declaration by features

TypeScript
1import { createQueryKeys, mergeQueryKeys } from '@lukemorales/query-key-factory'2 3// my-api/users.ts4export const usersKeys = createQueryKeys('users')5 6// my-api/todos.ts7export const todosKeys = createQueryKeys('todos', {8  completed: null,9  search: (query: string, limit = 15) => [query, limit],10  byId: (todoId: string) => ({ todoId }),11})12 13// my-api/index.ts14export 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.byId(todoId), fetchSingleTodo)7 8  const mutation = useMutation(completeTodo, {9    onSuccess: () => {10      // Invalidate and refetch11      queryClient.invalidateQueries(queryKeys.todos.completed)12    },13  })14 15  return (16    <div>17      <h1>18        {query.data?.title}19      </h1>2021      <p>22        {query.data?.description}23      </p>2425      <button26        onClick={() => {27          mutation.mutate({ todoId })28        }}29      >30        Complete Todo31      </button>32    </div>33  )34}

Check the complete documentation on GitHub.

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

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

译自上游 (未记录版本)