Skip to main content

Overview

The MutationCache is responsible for storing and managing all Mutation instances. It handles mutation scoping, execution ordering, and provides methods to access and manipulate mutations.

Constructor

const mutationCache = new MutationCache(config?: MutationCacheConfig)
config
MutationCacheConfig
Configuration options for the MutationCache
Example:
const mutationCache = new MutationCache({
  onError: (error, variables, onMutateResult, mutation, context) => {
    console.error('Mutation error:', error)
  },
  onSuccess: (data, variables, onMutateResult, mutation, context) => {
    console.log('Mutation success')
  },
})

Methods

build()

Builds a new mutation instance.
const mutation = mutationCache.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
Mutation options
state
MutationState
Initial state for the mutation
Returns: A new Mutation instance

add()

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

remove()

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

clear()

Removes all mutations from the cache.
mutationCache.clear(): void
Example:
mutationCache.clear()

getAll()

Returns all mutations in the cache.
const mutations = mutationCache.getAll(): Array<Mutation>
Returns: Array of all Mutation instances Example:
const allMutations = mutationCache.getAll()
console.log(`Total mutations: ${allMutations.length}`)

find()

Finds a single mutation that matches the filters.
const mutation = mutationCache.find<TData, TError, TVariables, TOnMutateResult>(
  filters: MutationFilters
): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined
filters
MutationFilters
required
Filters to match mutations
Returns: The first matching Mutation or undefined Example:
const mutation = mutationCache.find({
  mutationKey: ['updateTodo'],
  exact: true,
})

findAll()

Finds all mutations that match the filters.
const mutations = mutationCache.findAll(filters?: MutationFilters): Array<Mutation>
filters
MutationFilters
Filters to match mutations
Returns: Array of matching Mutation instances Example:
// Find all pending mutations
const pendingMutations = mutationCache.findAll({ status: 'pending' })

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

canRun()

Determines if a mutation can run based on scoping rules.
const canRun = mutationCache.canRun(mutation: Mutation): boolean
mutation
Mutation
required
The mutation to check
Returns: true if the mutation can run, false otherwise
Mutations with the same scope ID execute sequentially. A mutation can run if there are no other pending mutations in its scope, or if it is the first pending mutation in the scope.

runNext()

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

notify()

Notifies all subscribers of a cache event.
mutationCache.notify(event: MutationCacheNotifyEvent): void
event
MutationCacheNotifyEvent
required
The event to notify subscribers about

subscribe()

Subscribes to cache events.
const unsubscribe = mutationCache.subscribe(
  listener: (event: MutationCacheNotifyEvent) => void
): () => void
listener
(event: MutationCacheNotifyEvent) => void
required
Callback function to handle cache events
Returns: Function to unsubscribe Example:
const unsubscribe = mutationCache.subscribe((event) => {
  if (event.type === 'added') {
    console.log('Mutation added')
  }
  if (event.type === 'updated') {
    console.log('Mutation updated')
  }
})

// Later, unsubscribe
unsubscribe()

resumePausedMutations()

Resumes all paused mutations.
const promise = mutationCache.resumePausedMutations(): Promise<unknown>
Returns: Promise that resolves when all paused mutations have continued Example:
await mutationCache.resumePausedMutations()
This is typically called automatically when the network comes back online.

Mutation Scoping

Mutations can be scoped using the scope option. Mutations with the same scope ID will execute sequentially rather than concurrently. Example:
const mutation1 = mutationCache.build(client, {
  mutationFn: async (variables) => {
    // First mutation
  },
  scope: { id: 'todos' },
})

const mutation2 = mutationCache.build(client, {
  mutationFn: async (variables) => {
    // Second mutation - will wait for mutation1 to complete
  },
  scope: { id: 'todos' },
})

Events

The MutationCache emits the following events:
  • added - When a mutation is added to the cache
  • removed - When a mutation is removed from the cache
  • updated - When a mutation’s state changes
  • observerAdded - When an observer subscribes to a mutation
  • observerRemoved - When an observer unsubscribes from a mutation
  • observerOptionsUpdated - When observer options are updated

Usage with QueryClient

const mutationCache = new MutationCache()

const queryClient = new QueryClient({
  mutationCache,
})

Build docs developers (and LLMs) love