Skip to main content

Optimistic updates

Update local Convex query results directly, then let Convex confirm or roll back the change.

An optimistic update changes local query results before the mutation response arrives. Convex rolls the overlay back when the mutation fails and reconciles it with confirmed server data when it succeeds.

Use optimism when the expected server result is predictable. Prefer the normal live update for complex authorization or server-generated values.

optimisticUpdate must be synchronous and return undefined. An async function or Promise-like return is rejected by the TypeScript contract and diagnosed at runtime for JavaScript or casted callers.

The local-store contract

The callback receives Convex's OptimisticLocalStore. It has three direct methods:

MethodUse
getQuery(query, args)Read one currently loaded exact query result
getAllQueries(query)Read every loaded argument variant of a query
setQuery(query, args, data)Replace or remove one exact local result

Treat every returned value as immutable. Create new arrays and objects before passing them back.

Regular query example

This example uses the todos table and functions from Protect data. The page loads api.todos.list with {} as its arguments.

ts
import type { Id } from '#convex/dataModel'
import { api } from '#convex/api'

const { user } = useConvexAuth()

const { mutate: addTodo } = useConvexMutation(api.todos.create, {
  optimisticUpdate: (store, args) => {
    const current = store.getQuery(api.todos.list, {})
    const ownerId = user.value?.id
    if (current === undefined || ownerId === undefined) return undefined

    const optimisticTodo = {
      _id: crypto.randomUUID() as Id<'todos'>,
      _creationTime: Date.now(),
      ownerId,
      text: args.text.trim(),
      completed: false,
      createdAt: Date.now(),
    }

    store.setQuery(api.todos.list, {}, [optimisticTodo, ...current])
    return undefined
  },
})

The optimistic item must contain every field of the document type, so that TypeScript accepts it. Its ID is temporary and must not be used as a durable external identifier.

Exact query arguments matter. Updating { organizationId } does not update another argument set automatically. Use getAllQueries() only when the product explicitly needs to update multiple variants.

Paginated example

Pagination results are stored as Convex pages. Update only pages that are already loaded and preserve their cursor metadata:

ts
const { mutate: sendMessage } = useConvexMutation(api.messages.send, {
  optimisticUpdate: (store, args) => {
    const optimisticMessage = {
      _id: crypto.randomUUID() as Id<'messages'>,
      _creationTime: Date.now(),
      channelId: args.channelId,
      body: args.body,
    }

    for (const loaded of store.getAllQueries(api.messages.list)) {
      if (
        loaded.value !== undefined &&
        loaded.args.channelId === args.channelId &&
        loaded.args.paginationOpts.cursor === null
      ) {
        store.setQuery(api.messages.list, loaded.args, {
          ...loaded.value,
          page: [optimisticMessage, ...loaded.value.page],
        })
      }
    }

    return undefined
  },
})

This does not create unloaded pages or change backend ordering. More complex pagination edits must preserve page boundaries and are often clearer when left to the confirmed live result.

Read from the store and from args

Convex runs a pending optimistic update again each time new server data arrives. Write the update so that every run gives the correct result:

  • Read the current result with store.getQuery(), not from the data of a query composable. data can be older than the store, and the update then writes old server values over new ones.
  • Read IDs from args, not from component state. If the page shows another record by then, component state contains the new ID, and the update changes the wrong query.
ts
const { mutate: renameBoard } = useConvexMutation(api.boards.rename, {
  optimisticUpdate: (store, args) => {
    const queryArgs = { boardId: args.boardId }
    const current = store.getQuery(api.boards.get, queryArgs)
    if (!current) return undefined

    store.setQuery(api.boards.get, queryArgs, { ...current, name: args.name })
    return undefined
  },
})

For example, a product configurator lets the server calculate the price after each change. A user changes two options quickly. When the first mutation finishes, Convex runs the second update again on the new server result. An update that reads the composable's data writes the old price back, and the page shows it until the second mutation finishes. An update that reads store.getQuery() keeps the new price.

Failure and identity behavior

Convex rolls back a failed optimistic change. Do not undo the same change yourself in a catch block.

An auth: 'none' query uses a physically separate anonymous Convex client and local store. A mutation on the primary client cannot update that anonymous view; it reconciles when its server result arrives.

When the signed-in user changes, the module replaces the Convex client and discards its optimistic changes. A mutation that was running at that moment may still have been saved on the server, even though the call rejects. Do not run it again automatically.