createOptimisticAction

Function: createOptimisticAction()

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

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

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.

Type Parameters

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

Function

A function that accepts variables of type TVariables and returns a 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 }),
    })
    return response.json()
  }
})

// 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 }),
    })
    return response.json()
  }
})

// Usage
const transaction = addTodo('New Todo Item')
Our Partners
Electric
Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.

Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.