APIs and SDKs

Advanced client patterns with @sanity/client

Learn about mutation options, request cancellation, and other advanced patterns when using the Sanity JavaScript client.

This guide covers advanced patterns for working with @sanity/client, including mutation options that control how changes are applied and techniques for canceling in-flight requests.

These patterns apply to any mutation method: create(), patch(), delete(), and transaction().commit(). See Creating and updating documents and Creating transactions for the basics.

Mutation options

Control how mutations execute with options for visibility, dry runs, and array key generation. These options apply to any mutation method, not only transactions.

Visibility: sync, async, and deferred

The visibility option controls when mutations become visible to queries:

  • sync: The mutation completes and indexes before returning. Queries immediately see the changes. This is the default behavior.
  • async: The mutation returns immediately but indexes in the background. Queries may not see changes right away.
  • deferred: The mutation queues for later processing. Use this for non-critical updates or bulk operations.

Dry run mode

Test mutations without applying changes using dryRun: true. The API validates the mutation and returns what would happen, but does not modify any documents:

Auto-generate array keys

By default, the client automatically generates _key values for array items. Disable this with autoGenerateArrayKeys: false if you want to provide your own keys:

Canceling requests

Cancel in-flight requests using AbortController or by unsubscribing from Observables. This is useful for cleaning up requests when components unmount or when user actions make a request obsolete.

Using AbortController

Pass an AbortSignal to any client method to enable cancellation:

Unsubscribing from Observables

When using the Observable API, unsubscribe to cancel the request:

React cleanup example

This example shows how to cancel requests when a React component unmounts:

Was this page helpful?