fix: 详情页局部更新后刷新冲突校验版本

- 上传配图、重生成答案等接口只返回局部字段,页面异步回读最新 updatedAt
- 保存前等待回读完成,避免本次修改被误判为他人并发编辑
- 保留共享成员并发编辑的 409 冲突校验
This commit is contained in:
margrop
2026-12-03 16:31:37 +08:00
parent f0107d3cdd
commit f4fab6f727

View File

@@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { ArrowLeft, FileQuestion, RefreshCw, Trash2 } from "lucide-react";
@@ -53,11 +53,15 @@ export default function ErrorDetailPage() {
// 复习状态由举一反三记录和掌握概率决定,随掌握面板的数据更新
const [masteryStatus, setMasteryStatus] = useState<MasteryStatus | null>(null);
const [savingDifficulty, setSavingDifficulty] = useState(false);
// 保存冲突校验使用的最新读取版本;其他接口只返回局部字段时异步回读刷新
const updatedAtRef = useRef<string | undefined>(undefined);
const pendingUpdatedAt = useRef<Promise<void> | null>(null);
const fetchItem = useCallback(async (id: string) => {
try {
const data = await apiClient.get<ErrorItemDetail>(`/api/error-items/${id}`);
setItem(data);
updatedAtRef.current = data.updatedAt;
} catch (error) {
frontendLogger.error('[ErrorDetail]', 'Failed to fetch error item', { error });
toast.error(t.common?.messages?.loadFailed || 'Failed to load item');
@@ -85,15 +89,32 @@ export default function ErrorDetailPage() {
}, [params.id, fetchItem]);
const updateItem = useCallback((fields: Partial<ErrorItemDetail>) => {
if (fields.updatedAt !== undefined) {
updatedAtRef.current = fields.updatedAt;
}
setItem((current) => current && { ...current, ...fields });
}, []);
// 局部更新接口(上传配图、重生成答案等)不返回 updatedAt:回读最新版本,
// 避免随后保存时把本次修改误判为他人并发编辑。
if (fields.updatedAt === undefined && params.id) {
pendingUpdatedAt.current = apiClient.get<ErrorItemDetail>(`/api/error-items/${params.id as string}`)
.then((data) => {
updatedAtRef.current = data.updatedAt;
setItem((current) => current && { ...current, updatedAt: data.updatedAt });
})
.catch((error) => frontendLogger.warn('[ErrorDetail]', 'Failed to refresh update timestamp', { error }));
}
}, [params.id]);
// 保存字段并合并到页面状态,失败时抛出,由各卡片提示;带上读取时的 updatedAt 供并发编辑校验
const saveFields = async (fields: Partial<ErrorItemDetail>) => {
if (!item) return;
if (pendingUpdatedAt.current) {
await pendingUpdatedAt.current;
pendingUpdatedAt.current = null;
}
const updated = await apiClient.put<Pick<ErrorItemDetail, "updatedAt">>(`/api/error-items/${item.id}`, {
...fields,
...(item.updatedAt ? { expectedUpdatedAt: item.updatedAt } : {}),
...(updatedAtRef.current ? { expectedUpdatedAt: updatedAtRef.current } : {}),
});
updateItem({ ...fields, ...(updated.updatedAt ? { updatedAt: updated.updatedAt } : {}) });
};