Skip to content

Updating Data

After an edit succeeds, every screen showing that profile should see the same value. A mutation is an explicit replacement of a key’s cached value. mutate() can store a direct value or compute one from the previous committed value; it does not send an HTTP write by itself.

Begin with a stable instance and keys shared by readers and writers. The examples below use the Profile representation from Getting Started, with readonly id, name, and role fields.

If you already have the replacement, commit it and await completion:

await query.mutate('/profile.json', { id: 1, name: 'Grace', role: 'Editor' }, {
expiration: () => 30_000,
})

The returned promise resolves to the committed value. Existing subscribers receive mutating with the pending promise and mutated with the value after the write. Objects are retained, not cloned. Replace objects or arrays rather than editing shared values in place.

Mutation lifetime defaults to zero milliseconds, even when the instance uses a longer fetch lifetime. Without the explicit callback above, the next ordinary read may show the replacement while revalidating it from the server. This can be useful for an approximation of server state; it can be surprising for local-only data.

Derive changes from the latest committed value

Section titled “Derive changes from the latest committed value”

Two controls can update the same value before either call finishes. Use functional mutations rather than capturing an earlier snapshot:

query.hydrate('selected-count', 0)
const first = query.mutate<number>('selected-count', (previous) => (previous ?? 0) + 1)
const second = query.mutate<number>('selected-count', (previous) => (previous ?? 0) + 1)
const results = await Promise.all([first, second])
console.log(results) // [1, 2]

Same-key mutations run and commit in call order, including direct values queued behind asynchronous resolvers. The second resolver reads the value committed by the first, not the value that existed when it was enqueued. Its optional second argument is that entry’s expiration Date; treat it as read-only. Missing data supplies undefined.

Different keys run independently. There is no multi-key transaction. If a detail page and several lists represent the same profile, updating the detail does not update the lists automatically.

Never await another mutation of the same key inside its resolver. The nested call waits behind the current call, which then waits for the nested call: neither can finish. Compose the change in one resolver or await a second mutation after the first returns. Function values are always interpreted as resolvers; wrap callable data in an object if you need to store it.

For correctness-first edits, perform the HTTP write inside the mutation resolver and return the server’s accepted representation. The example assumes your backend implements PATCH /api/profiles/1, accepts { name: string }, and returns a full JSON profile. The static quickstart server does not implement this endpoint.

In your application’s data module, with its shared query instance and Profile type already defined, add this function:

/** Serializes profile saves and commits only an accepted server representation. */
export async function renameProfile(name: string): Promise<Profile> {
return query.mutate<Profile>('/api/profiles/1', async () => {
const response = await fetch('/api/profiles/1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
})
if (!response.ok) throw new Error(`profile save failed: ${response.status}`)
const profile: Profile = await response.json()
return profile
}, { expiration: () => 30_000 })
}

As with a typed read, the annotation does not validate JSON. Validate the response if your trust boundary requires it, following the validated fetcher pattern. Your backend must enforce authentication, authorization, input validation, and any CSRF protection; a cache mutation supplies none of those.

The resolver does not receive a query abort signal. query.abort() cancels reads, not mutation functions or queued server writes. If mutation cancellation is a product requirement, give your own write transport an appropriate controller and define how the server handles an ambiguous interrupted write.

On success, profile readers using /api/profiles/1 observe the returned representation. Afterward, invalidate affected list keys deliberately. If you must serialize server side effects, start them inside the resolver as above, not before enqueuing it.

If a resolver or its expiration callback throws, that mutation rejects before changing the stored value. The last committed value remains. Later same-key mutations still run; a failed queue entry does not poison the queue.

Catch each returned promise where the application can inform the user:

try {
await renameProfile('Grace')
} catch (error) {
console.error('Name was not saved:', error)
}

Mutation failures do not emit the core fetch error event, and there is no mutation error cache or automatic rollback callback. In React, the data hook also observes the mutation promise through a transition; do not assume catching the action promise prevents every transition error. Keep an error boundary around the view.

Add optimism without restoring obsolete snapshots

Section titled “Add optimism without restoring obsolete snapshots”

An optimistic update displays the intended result before the server confirms it. The safest starting point is a view-local optimistic value while the cache still represents committed data. For React, useOptimistic can display a pending name while renameProfile() runs; when the action ends, the optimistic overlay disappears and the view uses committed query data again.

For a React form, export Profile and renameProfile from your data module (profile-data.ts below). This focused component assumes a provider, Suspense, and an error boundary above it, using the same query instance as that module. It shows the intended name only in this view while the serialized save runs:

import { useOptimistic, useState, useTransition } from 'react'
import { useQuery } from '@studiolambda/query/react'
import { renameProfile, type Profile } from './profile-data'
/** Adds a view-local optimistic name without restoring old shared-cache snapshots. */
export function RenameProfile() {
const { data } = useQuery<Profile>('/api/profiles/1')
const [name, setName] = useOptimistic(data.name)
const [isPending, startTransition] = useTransition()
const [message, setMessage] = useState('')
function onRename(): void {
startTransition(async () => {
setName('Grace')
setMessage('')
try {
await renameProfile('Grace')
} catch (error) {
setMessage(error instanceof Error ? error.message : 'Name was not saved')
}
})
}
return (
<section>
<p>{name}</p>
<button disabled={isPending} onClick={onRename}>Rename to Grace</button>
<p role="status">{message}</p>
</section>
)
}

On success the committed profile supplies the name. On failure the optimistic overlay is removed; the error boundary remains necessary because the Query reader also observes mutation transitions. This overlay does not update other views before server confirmation.

You can instead commit an optimistic value with mutate(), but Query does not save or restore the previous value for you. A common “snapshot → optimistic write → restore snapshot on failure” pattern can overwrite another edit that committed during the request. Only use that pattern when your application serializes the entire operation and prevents conflicting writes; otherwise use view-local optimism or reconcile from the server after a failure. Serialization of individual mutate() calls does not make a sequence of several calls atomic.

Keep the server-confirmed baseline above until you have defined concurrent-edit and recovery behavior. A successful write followed by a failed revalidation is also different from a failed write: do not tell the user their save failed merely because a later refresh failed.

A successful mutation or hydration commit supersedes older pending reads of the same key. Those reads may still finish for their original callers, but cannot overwrite the newer cache value, remove it on failure, or emit resolved/error completion events. No transport cancellation is requested by the local write itself.

An immediately stale local commit can start a new revalidation without waiting for that older request to settle. Later reads and later local commits can still replace the value normally. This is not server-side conflict detection, nor a rule that mutations always beat every fetch forever.

Hydration and forgetting do not join the mutation queue. A queued mutation can commit after you seed or remove a key. For an account change, dispose the old UI and use a new isolated instance instead of assuming a single forget call cancels pending writes. Continue with cancellation for read ownership and events for observing commits.