Token导航 LogoToken导航TokenDH.com
待分类需要联网github未标认证来源可访问许可证需确认审计未展示

db-core%2fmutations-optimisticdb core%2fmutations 乐观

Agent Skill

db-core%2fmutations-optimistic 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

233

周安装

10

GitHub Stars

3,720

下载量

82
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:db-core%2fmutations-optimistic(db core%2fmutations 乐观)
来源仓库:https://github.com/tanstack/db
仓库路径:skills/db-core%2Fmutations-optimistic
安装命令:
npx skills add https://github.com/tanstack/db --skill db-core/mutations-optimistic
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/tanstack/db --skill db-core/mutations-optimistic

简介

db-core/mutations-optimistic 实现 TanStack DB 的乐观更新机制,提升用户界面响应速度。

  • 它在提交后端前临时应用变更,收到确认后固化状态,失败时自动回滚,避免阻塞操作。
  • 使用时需先设置 collection 的 onInsert/onUpdate 处理器,并在 mutation 中返回 Promise 结果。
  • 建议结合 Zod 校验输入,防止无效数据进入乐观层导致后续同步失败。
  • db-core%2fmutations-optimistic 属于待分类类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Mutations & Optimistic State

Depends on: db-core/collection-setup -- you need a configured collection (with getKey, sync adapter, and optionally onInsert/onUpdate/onDelete handlers) before you can mutate.

TanStack DB mutations follow a unidirectional loop: optimistic mutation -> handler persists to backend -> sync back -> confirmed state. Optimistic state is applied in the current tick and dropped when the handler resolves.


Setup -- Collection Write Operations

insert

// Single item
todoCollection.insert({
  id: crypto.randomUUID(),
  text: 'Buy groceries',
  completed: false,
})

// Multiple items
todoCollection.insert([
  { id: crypto.randomUUID(), text: 'Buy groceries', completed: false },
  { id: crypto.randomUUID(), text: 'Walk dog', completed: false },
])

// With metadata / non-optimistic
todoCollection.insert(item, { metadata: { source: 'import' } })
todoCollection.insert(item, { optimistic: false })

update (Immer-style draft proxy)

// Single item -- mutate the draft, do NOT reassign it
todoCollection.update(todo.id, (draft) => {
  draft.completed = true
  draft.completedAt = new Date()
})

// Multiple items
todoCollection.update([id1, id2], (drafts) => {
  drafts.forEach((d) => {
    d.completed = true
  })
})

// With metadata
todoCollection.update(
  todo.id,
  { metadata: { reason: 'user-edit' } },
  (draft) => {
    draft.text = 'Updated'
  },
)

delete

todoCollection.delete(todo.id)
todoCollection.delete([id1, id2])
todoCollection.delete(todo.id, { metadata: { reason: 'completed' } })

All three return a Transaction object. Use tx.isPersisted.promise to await persistence or catch rollback errors.


Core Patterns

1. createOptimisticAction -- intent-based mutations

Use when the optimistic change is a *guess* at how the server will transform the data, or when you need to mutate multiple collections atomically.

import { createOptimisticAction } from '@tanstack/db'

const likePost = createOptimisticAction<string>({
  // MUST be synchronous -- applied in the current tick
  onMutate: (postId) => {
    postCollection.update(postId, (draft) => {
      draft.likeCount += 1
      draft.likedByMe = true
    })
  },
  mutationFn: async (postId, { transaction }) => {
    await api.posts.like(postId)
    // IMPORTANT: wait for server state to sync back before returning
    await postCollection.utils.refetch()
  },
})

// Returns a Transaction
const tx = likePost(postId)
await tx.isPersisted.promise

Multi-collection example:

const createProject = createOptimisticAction<{ name: string; ownerId: string }>(
  {
    onMutate: ({ name, ownerId }) => {
      projectCollection.insert({ id: crypto.randomUUID(), name, ownerId })
      userCollection.update(ownerId, (d) => {
        d.projectCount += 1
      })
    },
    mutationFn: async ({ name, ownerId }) => {
      await api.projects.create({ name, ownerId })
      await Promise.all([
        projectCollection.utils.refetch(),
        userCollection.utils.refetch(),
      ])
    },
  },
)

2. createPacedMutations -- auto-save with debounce / throttle / queue

import { createPacedMutations, debounceStrategy } from '@tanstack/db'

const autoSaveNote = createPacedMutations<string>({
  onMutate: (text) => {
    noteCollection.update(noteId, (draft) => {
      draft.body = text
    })
  },
  mutationFn: async ({ transaction }) => {
    const mutation = transaction.mutations[0]
    await api.notes.update(mutation.key, mutation.changes)
    await noteCollection.utils.refetch()
  },
  strategy: debounceStrategy({ wait: 500 }),
})

// Each call resets the debounce timer; mutations merge into one transaction
autoSaveNote('Hello')
autoSaveNote('Hello, world') // only this version persists

Other strategies:

import { throttleStrategy, queueStrategy } from '@tanstack/db'

// Evenly spaced (sliders, scroll)
throttleStrategy({ wait: 200, leading: true, trailing: true })

// Sequential FIFO -- every mutation persisted in order
queueStrategy({ wait: 0, maxSize: 100 })

3. createTransaction -- manual batching

import { createTransaction } from '@tanstack/db'

const tx = createTransaction({
  autoCommit: false, // wait for explicit commit()
  mutationFn: async ({ transaction }) => {
    await api.batchUpdate(transaction.mutations)
  },
})

tx.mutate(() => {
  todoCollection.update(id1, (d) => {
    d.status = 'reviewed'
  })
  todoCollection.update(id2, (d) => {
    d.status = 'reviewed'
  })
})

// User reviews... then commits or rolls back
await tx.commit()
// OR: tx.rollback()

Inside tx.mutate(() => {...}), the transaction is pushed onto an ambient stack. Any collection.insert/update/delete call joins the ambient transaction automatically via getActiveTransaction().

4. Mutation handler with refetch (QueryCollection pattern)

const todoCollection = createCollection(
  queryCollectionOptions({
    queryKey: ['todos'],
    queryFn: () => api.todos.getAll(),
    getKey: (t) => t.id,
    onInsert: async ({ transaction }) => {
      await Promise.all(
        transaction.mutations.map((m) => api.todos.create(m.modified)),
      )
      // IMPORTANT: handler must not resolve until server state is synced back
      // QueryCollection auto-refetches after handler completes
    },
    onUpdate: async ({ transaction }) => {
      await Promise.all(
        transaction.mutations.map((m) =>
          api.todos.update(m.original.id, m.changes),
        ),
      )
    },
    onDelete: async ({ transaction }) => {
      await Promise.all(
        transaction.mutations.map((m) => api.todos.delete(m.original.id)),
      )
    },
  }),
)

For ElectricCollection, return {txid} instead of refetching:

onUpdate: async ({ transaction }) => {
  const txids = await Promise.all(
    transaction.mutations.map(async (m) => {
      const res = await api.todos.update(m.original.id, m.changes)
      return res.txid
    }),
  )
  return { txid: txids }
}

Common Mistakes

CRITICAL: Passing an object to update() instead of a draft callback

// WRONG -- silently fails or throws
collection.update(id, { ...item, title: 'new' })

// CORRECT -- mutate the draft proxy
collection.update(id, (draft) => {
  draft.title = 'new'
})

CRITICAL: Hallucinating mutation API signatures

The most common AI-generated errors:

  • Inventing handler signatures (e.g. onMutate on a collection config)
  • Confusing createOptimisticAction with createTransaction
  • Wrong PendingMutation property names (mutation.data does not exist -- use mutation.modified, mutation.changes, mutation.original)
  • Missing the ambient transaction pattern

Always reference the exact types in references/transaction-api.md.

CRITICAL: onMutate returning a Promise

onMutate in createOptimisticAction must be synchronous. Optimistic state is applied in the current tick. Returning a Promise throws OnMutateMustBeSynchronousError.

// WRONG
createOptimisticAction({
  onMutate: async (text) => {
    collection.insert({ id: await generateId(), text })
  },
  ...
})

// CORRECT
createOptimisticAction({
  onMutate: (text) => {
    collection.insert({ id: crypto.randomUUID(), text })
  },
  ...
})

CRITICAL: Mutations without handler or ambient transaction

Collection mutations require either:

  1. An onInsert/onUpdate/onDelete handler on the collection, OR
  2. An ambient transaction from createTransaction/createOptimisticAction

Without either, throws MissingInsertHandlerError (or the Update/Delete variant).

HIGH: Calling.mutate() after transaction is no longer pending

Transactions only accept new mutations while in pending state. Calling mutate() after commit() or rollback() throws TransactionNotPendingMutateError. Create a new transaction instead.

HIGH: Changing primary key via update

The update proxy detects key changes and throws KeyUpdateNotAllowedError. Primary keys are immutable once set. If you need a different key, delete and re-insert.

HIGH: Inserting item with duplicate key

If an item with the same key already exists (synced or optimistic), throws DuplicateKeyError. Always generate a unique key (e.g. crypto.randomUUID()) or check before inserting.

HIGH: Not awaiting refetch after mutation in query collection handler

The optimistic state is held only until the handler resolves. If the handler returns before server state has synced back, optimistic state is dropped and users see a flash of missing data.

// WRONG -- optimistic state dropped before new server state arrives
onInsert: async ({ transaction }) => {
  await api.createTodo(transaction.mutations[0].modified)
  // missing: await collection.utils.refetch()
}

// CORRECT
onInsert: async ({ transaction }) => {
  await api.createTodo(transaction.mutations[0].modified)
  await collection.utils.refetch()
}

Tension: Optimistic Speed vs. Data Consistency

Instant optimistic updates create a window where client state diverges from server state. If the handler fails, the rollback removes the optimistic state -- which can discard user work the user thought was saved. Consider:

  • Showing pending/saving indicators so users know state is unconfirmed
  • Using {optimistic: false} for destructive operations
  • Designing idempotent server endpoints so retries are safe
  • Handling tx.isPersisted.promise rejection to surface errors to the user

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.54%
按下载量换算28

Claude

28.89%
按下载量换算24

Cursor

19.46%
按下载量换算16

Gemini CLI

9.01%
按下载量换算7

安全审计

暂无安全审计结果可展示。

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills