From 70e6c958a5a624e1d3ce51ff119a281032addf1a Mon Sep 17 00:00:00 2001
From: soryu <soryu@soryu.co>
Date: Wed, 24 Dec 2025 01:49:05 +0000
Subject: Fixup: Update overwrite mechanism

---
 makima/frontend/src/routes/files.tsx | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

(limited to 'makima/frontend/src/routes/files.tsx')

diff --git a/makima/frontend/src/routes/files.tsx b/makima/frontend/src/routes/files.tsx
index 2a75218..989ea44 100644
--- a/makima/frontend/src/routes/files.tsx
+++ b/makima/frontend/src/routes/files.tsx
@@ -24,6 +24,12 @@ export default function FilesPage() {
   const [hasLocalChanges, setHasLocalChanges] = useState(false);
   const [isActivelyEditing, setIsActivelyEditing] = useState(false);
   const pendingUpdateRef = useRef(false);
+  const remoteUpdateRef = useRef<FileUpdateEvent | null>(null);
+
+  // Keep ref in sync with state to avoid stale closures
+  useEffect(() => {
+    remoteUpdateRef.current = remoteUpdate;
+  }, [remoteUpdate]);
 
   // Load file detail when URL has an id
   useEffect(() => {
@@ -124,8 +130,9 @@ export default function FilesPage() {
         newBody[index] = element;
 
         // If there's a pending remote update, fetch latest version first
+        // Use ref to get current value (avoids stale closure)
         let versionToUse = fileDetail.version;
-        if (remoteUpdate) {
+        if (remoteUpdateRef.current) {
           const latest = await fetchFile(id);
           if (latest) {
             versionToUse = latest.version;
@@ -149,7 +156,7 @@ export default function FilesPage() {
         }
       }
     },
-    [fileDetail, id, editFile, remoteUpdate, fetchFile]
+    [fileDetail, id, editFile, fetchFile]
   );
 
   const handleBodyReorder = useCallback(
@@ -161,8 +168,9 @@ export default function FilesPage() {
         newBody.splice(toIndex, 0, movedElement);
 
         // If there's a pending remote update, fetch latest version first
+        // Use ref to get current value (avoids stale closure)
         let versionToUse = fileDetail.version;
-        if (remoteUpdate) {
+        if (remoteUpdateRef.current) {
           const latest = await fetchFile(id);
           if (latest) {
             versionToUse = latest.version;
@@ -186,7 +194,7 @@ export default function FilesPage() {
         }
       }
     },
-    [fileDetail, id, editFile, remoteUpdate, fetchFile]
+    [fileDetail, id, editFile, fetchFile]
   );
 
   const handleCreate = useCallback(async () => {
-- 
cgit v1.2.3

