Skip to main content

Overview

The MutationObserver class is used to subscribe to a mutation and receive reactive updates when the mutation’s state changes. It’s the foundation for framework-specific hooks like useMutation in React.

Constructor

QueryClient
required
The QueryClient instance
MutationObserverOptions
required
Options for the mutation observer
Example:

Methods

subscribe()

Subscribes to mutation updates.
(result: MutationObserverResult<TData, TError, TVariables, TOnMutateResult>) => void
required
Callback function that receives mutation results
Returns: Function to unsubscribe Example:

getCurrentResult()

Returns the current result without subscribing.
Returns: Current mutation result
object

setOptions()

Updates the observer’s options.
MutationObserverOptions
required
New options for the observer
Example:

mutate()

Executes the mutation.
TVariables
required
Variables to pass to the mutation function
MutateOptions
Additional options for this specific mutation call
Returns: Promise that resolves with the mutation data or rejects with the error Example:

reset()

Resets the mutation to its initial idle state.
Example:
Resetting removes the observer from the current mutation. A new call to mutate() will create a new mutation instance.

Properties

options

The current options for the observer.

Type Parameters

  • TData - The type of data returned by the mutation function
  • TError - The type of error that can be thrown (defaults to DefaultError)
  • TVariables - The type of variables passed to the mutation function (defaults to void)
  • TOnMutateResult - The type of value returned by the onMutate callback

Usage Example

Optimistic Updates

The MutationObserver is commonly used for optimistic updates: