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

MutationCache

The MutationCache is the storage for mutations.

Normally, you will not interact with the MutationCache directly and instead use the QueryClient.

TypeScript
1import { MutationCache } from '@tanstack/react-query'2 3const mutationCache = new MutationCache({4  onError: error => {5    console.log(error)6  },7  onSuccess: data => {8    console.log(data)9  },10})

Its available methods are:

Options

  • onError?: (error: unknown, variables: unknown, context: unknown, mutation: Mutation) => void
    • Optional
    • This function will be called if some mutation encounters an error.
  • onSuccess?: (data: unknown, variables: unknown, context: unknown, mutation: Mutation) => void
    • Optional
    • This function will be called if some mutation is successful.
  • onMutate?: (variables: unknown, mutation: Mutation) => void
    • Optional
    • This function will be called before some mutation executes.

Global callbacks

The onError, onSuccess and onMutate callbacks on the MutationCache can be used to handle these events on a global level. They are different to defaultOptions provided to the QueryClient because:

  • defaultOptions can be overridden by each Mutation - the global callbacks will always be called.
  • onMutate does not allow returning a context value.

mutationCache.getAll

getAll returns all mutations within the cache.

Note: This is not typically needed for most applications, but can come in handy when needing more information about a mutation in rare scenarios

TypeScript
1const mutations = mutationCache.getAll()

Returns

  • Mutation[]
    • Mutation instances from the cache

mutationCache.subscribe

The subscribe method can be used to subscribe to the mutation cache as a whole and be informed of safe/known updates to the cache like mutation states changing or mutations being updated, added or removed.

TypeScript
1const callback = event => {2  console.log(event.type, event.mutation)3}4 5const unsubscribe = mutationCache.subscribe(callback)

Options

  • callback: (mutation?: MutationCacheNotifyEvent) => void
    • This function will be called with the mutation cache any time it is updated.

Returns

  • unsubscribe: Function => void
    • This function will unsubscribe the callback from the mutation cache.

mutationCache.clear

The clear method can be used to clear the cache entirely and start fresh.

TypeScript
1mutationCache.clear()

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

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

译自上游 (未记录版本)