Skip to main content
The MutationCache is responsible for storing and managing all Mutation instances. It’s the underlying storage mechanism used by QueryClient for mutations.

Constructor

Creates a new MutationCache instance.
const mutationCache = new MutationCache(config?: MutationCacheConfig)
config
MutationCacheConfig
Configuration options for the MutationCache

Example

import { MutationCache } from '@tanstack/query-core'

const mutationCache = new MutationCache({
  onError: (error, variables, onMutateResult, mutation) => {
    console.error('Mutation failed:', error)
  },
  onSuccess: (data, variables, onMutateResult, mutation) => {
    console.log('Mutation succeeded:', data)
  },
})

Methods

build

Builds a new mutation instance.
build<TData, TError, TVariables, TOnMutateResult>(
  client: QueryClient,
  options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,
  state?: MutationState<TData, TError, TVariables, TOnMutateResult>
): Mutation<TData, TError, TVariables, TOnMutateResult>
client
QueryClient
required
The QueryClient instance.
options
MutationOptions
required
Options for the mutation.
state
MutationState
Optional initial state for the mutation.
Mutation
Mutation
Returns a new Mutation instance.

add

Adds a mutation to the cache.
add(mutation: Mutation): void
mutation
Mutation
required
The mutation instance to add.

remove

Removes a mutation from the cache.
remove(mutation: Mutation): void
mutation
Mutation
required
The mutation instance to remove.

clear

Clears all mutations from the cache.
clear(): void

Example

mutationCache.clear()

getAll

Returns all mutations in the cache.
getAll(): Array<Mutation>
Array<Mutation>
Array
Returns an array of all Mutation instances in the cache.

find

Finds a single mutation matching the provided filters.
find<TData, TError, TVariables, TOnMutateResult>(
  filters: MutationFilters
): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined
filters
MutationFilters
required
Filters to match mutations.
Mutation | undefined
Mutation
Returns the first matching Mutation instance, or undefined if not found.

findAll

Finds all mutations matching the provided filters.
findAll(filters?: MutationFilters): Array<Mutation>
filters
MutationFilters
Filters to match mutations. If not provided, returns all mutations.
Array<Mutation>
Array
Returns an array of all matching Mutation instances.

Example

// Find all pending mutations
const pendingMutations = mutationCache.findAll({ status: 'pending' })

// Find mutations with a specific key
const todoMutations = mutationCache.findAll({ 
  mutationKey: ['todos'] 
})

// Find mutations with custom predicate
const mutations = mutationCache.findAll({
  predicate: (mutation) => mutation.state.isPaused
})

notify

Notifies all cache listeners of an event.
notify(event: MutationCacheNotifyEvent): void
event
MutationCacheNotifyEvent
required
The event to notify listeners about.

subscribe

Subscribes to cache events.
subscribe(listener: MutationCacheListener): () => void
listener
(event: MutationCacheNotifyEvent) => void
required
Function called when cache events occur.
() => void
function
Returns an unsubscribe function.

Example

const unsubscribe = mutationCache.subscribe((event) => {
  console.log('Mutation cache event:', event.type)
  
  if (event.type === 'added') {
    console.log('Mutation added:', event.mutation.mutationId)
  } else if (event.type === 'updated') {
    console.log('Mutation updated:', event.mutation.state.status)
  }
})

// Later, unsubscribe
unsubscribe()

resumePausedMutations

Resumes all paused mutations.
resumePausedMutations(): Promise<unknown>
Promise<unknown>
Promise
Returns a promise that resolves when all paused mutations have been resumed.

Example

await mutationCache.resumePausedMutations()

Events

The MutationCache emits the following events:

added

Fired when a mutation is added to the cache.
{
  type: 'added'
  mutation: Mutation
}

removed

Fired when a mutation is removed from the cache.
{
  type: 'removed'
  mutation: Mutation
}

updated

Fired when a mutation is updated.
{
  type: 'updated'
  mutation: Mutation
  action: Action
}

observerAdded

Fired when an observer is added to a mutation.
{
  type: 'observerAdded'
  mutation: Mutation
  observer: MutationObserver
}

observerRemoved

Fired when an observer is removed from a mutation.
{
  type: 'observerRemoved'
  mutation: Mutation
  observer: MutationObserver
}

observerOptionsUpdated

Fired when observer options are updated.
{
  type: 'observerOptionsUpdated'
  mutation?: Mutation
  observer: MutationObserver
}

Mutation Scopes

The MutationCache supports mutation scoping, which allows you to control the order of mutation execution. Mutations with the same scope ID will execute sequentially.

canRun

Checks if a mutation can run based on its scope.
canRun(mutation: Mutation): boolean
mutation
Mutation
required
The mutation to check.
boolean
boolean
Returns true if the mutation can run, false if it must wait for another mutation in the same scope.

runNext

Runs the next pending mutation in the same scope.
runNext(mutation: Mutation): Promise<unknown>
mutation
Mutation
required
The mutation that just completed.
Promise<unknown>
Promise
Returns a promise that resolves when the next mutation continues.

Usage with QueryClient

While you can use MutationCache directly, it’s typically used through a QueryClient:
import { QueryClient, MutationCache } from '@tanstack/query-core'

// Custom cache with event handlers
const mutationCache = new MutationCache({
  onSuccess: (data) => {
    console.log('Global mutation success:', data)
  },
  onError: (error) => {
    console.error('Global mutation error:', error)
  },
})

// Use custom cache with QueryClient
const queryClient = new QueryClient({
  mutationCache,
})

Build docs developers (and LLMs) love