📄 tanstack/db/latest/docs/reference/functions/createOptimisticAction

File: createOptimisticAction.md | Updated: 11/15/2025

Source: https://tanstack.com/db/latest/docs/reference/functions/createOptimisticAction



TanStack

DB v0v0

Search...

+ K

Auto

Log In

TanStack StartRC

Docs Examples GitHub Contributors

TanStack Router

Docs Examples GitHub Contributors

TanStack Query

Docs Examples GitHub Contributors

TanStack Table

Docs Examples Github Contributors

TanStack Formnew

Docs Examples Github Contributors

TanStack DBbeta

Docs Github Contributors

TanStack Virtual

Docs Examples Github Contributors

TanStack Paceralpha

Docs Examples Github Contributors

TanStack Storealpha

Docs Examples Github Contributors

TanStack Devtoolsalpha

Docs Github Contributors

More Libraries

Maintainers Partners Support Learn StatsBETA Discord Merch Blog GitHub Ethos Brand Guide

Documentation

Framework

React logo

React

Version

Latest

Search...

+ K

Menu

Getting Started

Guides

Collections

Frameworks

Community

API Reference

Framework

React logo

React

Version

Latest

Menu

Getting Started

Guides

Collections

Frameworks

Community

API Reference

On this page

createOptimisticAction

Copy Markdown

Function: createOptimisticAction()
==================================

ts

function createOptimisticAction<TVariables>(options): (variables) => Transaction;


function createOptimisticAction<TVariables>(options): (variables) => Transaction;

Defined in: packages/db/src/optimistic-action.ts:54

Creates an optimistic action function that applies local optimistic updates immediately before executing the actual mutation on the server.

This pattern allows for responsive UI updates while the actual mutation is in progress. The optimistic update is applied via the onMutate callback, and the server mutation is executed via the mutationFn.

Important: Inside your mutationFn, you must ensure that your server writes have synced back before you return, as the optimistic state is dropped when you return from the mutation function. You generally use collection-specific helpers to do this, such as Query's utils.refetch(), direct write APIs, or Electric's utils.awaitTxId().

Type Parameters
---------------
### TVariables

TVariables = unknown

The type of variables that will be passed to the action function

Parameters
----------
### options

CreateOptimisticActionsOptions <TVariables>

Configuration options for the optimistic action

Returns
-------

A function that accepts variables of type TVariables and returns a Transaction

ts

(variables): Transaction;


(variables): Transaction;

### Parameters #### variables

TVariables

### Returns

Transaction

Example
-------

ts

const addTodo = createOptimisticAction<string>({
  onMutate: (text) => {
    // Instantly applies local optimistic state
    todoCollection.insert({
      id: uuid(),
      text,
      completed: false
    })
  },
  mutationFn: async (text, params) => {
    // Persist the todo to your backend
    const response = await fetch('/api/todos', {
      method: 'POST',
      body: JSON.stringify({ text, completed: false }),
    })
    const result = await response.json()

    // IMPORTANT: Ensure server writes have synced back before returning
    // This ensures the optimistic state can be safely discarded
    await todoCollection.utils.refetch()

    return result
  }
})

// Usage
const transaction = addTodo('New Todo Item')


const addTodo = createOptimisticAction<string>({
  onMutate: (text) => {
    // Instantly applies local optimistic state
    todoCollection.insert({
      id: uuid(),
      text,
      completed: false
    })
  },
  mutationFn: async (text, params) => {
    // Persist the todo to your backend
    const response = await fetch('/api/todos', {
      method: 'POST',
      body: JSON.stringify({ text, completed: false }),
    })
    const result = await response.json()

    // IMPORTANT: Ensure server writes have synced back before returning
    // This ensures the optimistic state can be safely discarded
    await todoCollection.utils.refetch()

    return result
  }
})

// Usage
const transaction = addTodo('New Todo Item')

Edit on GitHub

createLiveQueryCollection

createTransaction

Partners Become a Partner

Code RabbitCode Rabbit CloudflareCloudflare AG GridAG Grid NetlifyNetlify NeonNeon WorkOSWorkOS ClerkClerk ConvexConvex ElectricElectric SentrySentry PrismaPrisma StrapiStrapi UnkeyUnkey

scarf analytics