跳到正文
Skillpedia
网站与界面(前端)48k · #4671

frontend-optimistic-mutations

它能做什么

这项技能可以让界面上的更新看起来即时完成。它会先立即更新界面,如果出现问题,就会把改动撤销,不留任何痕迹。

适用场景

  • ✓把某个事项标记为已完成的时候。
  • ✓修改订单状态的时候。
  • ✓对列表中的项目重新排序的时候。

技能链接

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/frontend-optimistic-mutations/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/frontend-optimistic-mutations/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“帮我把发票标记为“已付款”的操作做得即时响应,但如果出错就回滚。”

每周 5 个新技能,1 分钟读完。

工作原理

你做出修改时,界面会马上更新。如果修改没能成功发送到服务器,界面就会恢复到之前的状态,就像什么都没发生过一样。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

Frontend Optimistic Mutations (the write path)

When to Use

Use this skill when you need a portable, framework-agnostic discipline for the write path of any React or React Native app using a query/cache layer. Codifies the optimistic-update lifecycle (cancel in-flight queries → snapshot every affected cache → patch instantly → roll back verbatim on error → invalidate on...

Portable skill — readable by Claude Code, OpenCode, Codex, Cursor, Windsurf, and others. This skill describes the discipline of the write path — optimistic updates, rollback, idempotency, cache coherence — not a UI library or a styling system. It builds directly on the frontend-data-contracts skill (writes go through the typed client) and the frontend-architecture skill (mutations live in modules/{feature}/hooks/, keyed by a factory).

The goal: a write feels instant (the UI reflects it before the server confirms), is safe (a failure restores the exact prior state, and a retry never double-charges), and leaves the cache coherent (the detail view and every list page agree). All three at once — that's the craft.


0. The five core ideas

  1. The optimistic lifecycle is fixed. cancel → snapshot → patch → (error: roll back) → (settle: invalidate). Every optimistic mutation follows the same five beats.
  2. Roll back verbatim. On failure, restore the exact snapshot taken before the patch — not a "best guess" re-derivation. Keep the snapshot in mutation context.
  3. Idempotency is generated once, not per attempt. The key is created at form init (or first intent), so a network retry replays the original server response instead of performing the action twice.
  4. Caches move in lock-step. A status change patches the detail cache and every list page that contains the entity, so badges never disagree across surfaces.
  5. Server state never enters the client store. Optimistic state lives in the query cache, not Zustand/Redux. The cache is the single source of truth for server data (per frontend-architecture §4).

1. When to be optimistic (and when not)

Situation Strategy
High-confidence, low-conflict write (toggle status, like, mark-paid, reorder) Optimistic — patch immediately, roll back on error.
Create that returns a server-generated id/number/total Pending state, then setQueryData from the server response. A temporary optimistic row is optional; reconcile on success.
Destructive or hard-to-reverse write (delete with cascade, send money) Confirm first, then optimistic or pending — never silent-optimistic.
Write whose result the user can't see yet (background job) Pending + toast, invalidate when done. No optimistic patch.

Optimism is a UX tool for writes you're confident will succeed. If failure is common or expensive to undo, prefer a pending state.


2. The optimistic lifecycle (TanStack Query)

The canonical shape. Each beat has a job; skipping one breaks correctness.

// modules/invoice/hooks/useInvoiceMutations.ts
interface MarkPaidContext {
  previousInvoice: Invoice | undefined; // detail snapshot
  previousLists: Array<[readonly unknown[], InvoiceListResponse]>; // every list page snapshot
}

export function useMarkInvoicePaid() {
  const queryClient = useQueryClient();
  const notifyError = useApiErrorToast();

  return useMutation<Invoice, ApiError, { id: InvoiceId }, MarkPaidContext>({
    mutationFn: ({ id }) => apiClient.post<Invoice>(INVOICE_API.markPaid(id)),

    // 1 + 2 + 3: cancel in-flight reads, snapshot, patch
    onMutate: async ({ id }) => {
      await queryClient.cancelQueries({ queryKey: invoiceKeys.all }); // (1) no late refetch clobber

      const detailKey = invoiceKeys.detail(id);

…
常见问题

“乐观更新”(optimistic update)是什么意思?

指界面在服务器确认修改成功之前,就先立即更新显示。就像你填完表单后,还没等系统真正保存,屏幕上就已经出现了“已保存”的提示。

什么是“回滚”(rollback)?

回滚是指在出错时,把修改恢复到修改前的确切状态。这样可以确保用户看到的不会是不一致或不正确的数据。

为什么列表和详情页的数据要保持一致?

这样可以保证整个应用中的信息前后一致。如果你在列表中把某个项目标记为已付款,那么其他显示该项目的地方(比如详情页)也应该立即同步更新。

详情

作者的原始描述

A portable, framework-agnostic discipline for the write path of any React or React Native app using a query/cache layer.

repo: sickn33/agentic-awesome-skills

热度

GitHub 星标
48k
排名
#4671
许可证
MIT
更新时间
2026/10/15

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能