From 06edc236a160c4d05e4a089fb274f58640929fa6 Mon Sep 17 00:00:00 2001 From: PJ Date: Fri, 7 Mar 2025 16:06:01 -0500 Subject: [PATCH] Fix refresh not working for React-based views The existing code had a race condition that let it get into a state where no further updates could take place. This revision ensures that the view remains subscribed so long as the container element remains unchanged. (It also removes the extra initialization state and lastReload state, relying on the fact that the refreshOperation is only triggered when a view transitions from hidden to visible, or when the index is changed.) This should reduce the number of React refreshes, as well as the overhead of repeatedly subscribing (and then unsubscribing) to the various events. --- src/ui/markdown.tsx | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/src/ui/markdown.tsx b/src/ui/markdown.tsx index 3d144ca1..2574f218 100644 --- a/src/ui/markdown.tsx +++ b/src/ui/markdown.tsx @@ -243,24 +243,13 @@ export function useIndexBackedState( initial: T, compute: () => Promise ): T { - let [initialized, setInitialized] = useState(false); let [state, updateState] = useState(initial); - let [lastReload, setLastReload] = useState(index.revision); - - // Initial setup to queue fetching the correct state. - if (!initialized) { - setLastReload(index.revision); - setInitialized(true); - - compute().then(updateState); - } // Updated on every container re-create; automatically updates state. useEffect(() => { const refreshOperation = () => { - if (lastReload != index.revision && container.isShown() && settings.refreshEnabled) { + if (container.isShown() && settings.refreshEnabled) { compute().then(updateState); - setLastReload(index.revision); } }; @@ -269,11 +258,14 @@ export function useIndexBackedState( // ...or when the DOM is shown (sidebar expands, tab selected, nodes scrolled into view). let nodeEvent = container.onNodeInserted(refreshOperation); + // Handle the initial refresh + compute().then(updateState); + return () => { app.workspace.offref(workEvent); nodeEvent(); }; - }, [container, lastReload]); + }, [container]); return state; }