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 )
Configuration options for the MutationCache onError
(error: DefaultError, variables: unknown, onMutateResult: unknown, mutation: Mutation, context: MutationFunctionContext) => Promise<unknown> | unknown
Global error handler called when any mutation errors
onSuccess
(data: unknown, variables: unknown, onMutateResult: unknown, mutation: Mutation, context: MutationFunctionContext) => Promise<unknown> | unknown
Global success handler called when any mutation succeeds
onMutate
(variables: unknown, mutation: Mutation, context: MutationFunctionContext) => Promise<unknown> | unknown
Global handler called before any mutation executes
onSettled
(data: unknown | undefined, error: DefaultError | null, variables: unknown, onMutateResult: unknown, mutation: Mutation, context: MutationFunctionContext) => Promise<unknown> | unknown
Global settled handler called when any mutation completes
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 >
Mutation options mutationFn
(variables: TVariables, context: MutationFunctionContext) => Promise<TData>
The function to execute the mutation
Unique key for the mutation
Scope for sequential mutation execution
Initial state for the mutation
Returns: A new Mutation instance
add()
Adds a mutation to the cache.
mutationCache . add ( mutation : Mutation ): void
The mutation instance to add
remove()
Removes a mutation from the cache.
mutationCache . remove ( mutation : Mutation ): void
The mutation instance to remove
clear()
Removes all mutations from the cache.
mutationCache . clear (): void
Example:
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 to match mutations Match mutation key exactly. Defaults to true for find().
status
'idle' | 'pending' | 'success' | 'error'
Filter by mutation status
predicate
(mutation: Mutation) => boolean
Custom predicate function
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 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
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 >
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 Emitted when a mutation is added Emitted when a mutation is removed Emitted when a mutation is updated Emitted when an observer is added
Emitted when an observer is removed
Emitted when observer options are updated
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 ,
})